JavaScript切片方法? [英] JavaScript slice method?
本文介绍了JavaScript切片方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个数组的元素切割成一个新的左右数组。我坚持如何开始这个。
I want to slice elements of one array into a new left and right array. I am stuck on how to start this.
推荐答案
鉴于此数组:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
如果要分割数组,使前4个项目转到左边的数组,其余的到正确的数组,然后执行此操作:
If you want to split the array so that the first 4 items go to the left array and the rest to the right array, then do this:
var leftArr = arr.slice(0, 4);
和
var rightArr = arr.slice(4);
你可以根据分割位置创建一个返回这两个数组的函数:
You can make a function that returns those two arrays based on the split-position:
function splitArr(arr, i) {
return [ arr.slice(0, i), arr.slice(i) ];
}
这篇关于JavaScript切片方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文