I have an array with a list of objects. I want to split this array at one particular index, say 4 (this in real is a variable). I want to store the second part of the split array into another array. Might be simple, but I am unable to think of a nice way to do this.
我有一个包含对象列表的数组。我想将这个数组拆分为一个特定的索引,比如4(实际上这是一个变量)。我想将split数组的第二部分存储到另一个数组中。可能很简单,但我无法想到一个很好的方法来做到这一点。
4 个解决方案
#1
38
Use slice, as such:
使用切片,如下:
var ar = [1,2,3,4,5,6];
var p1 = ar.slice(0,4);
var p2 = ar.slice(4);
#2
5
You can use Array@splice
to chop all elements after a specified index off the end of the array and return them:
您可以使用Array @ splice在数组末尾的指定索引之后切断所有元素并返回它们:
x = ["a", "b", "c", "d", "e", "f", "g"];
y = x.splice(3);
console.log(x); // ["a", "b", "c"]
console.log(y); // ["d", "e", "f", "g"]
#3
#4
1
You can also use underscore/lodash wrapper:
你也可以使用下划线/ lodash包装器:
var ar = [1,2,3,4,5,6];
var p1 = _.first(ar, 4);
var p2 = _.rest(ar, 4);
#1
38
Use slice, as such:
使用切片,如下:
var ar = [1,2,3,4,5,6];
var p1 = ar.slice(0,4);
var p2 = ar.slice(4);
#2
5
You can use Array@splice
to chop all elements after a specified index off the end of the array and return them:
您可以使用Array @ splice在数组末尾的指定索引之后切断所有元素并返回它们:
x = ["a", "b", "c", "d", "e", "f", "g"];
y = x.splice(3);
console.log(x); // ["a", "b", "c"]
console.log(y); // ["d", "e", "f", "g"]
#3
#4
1
You can also use underscore/lodash wrapper:
你也可以使用下划线/ lodash包装器:
var ar = [1,2,3,4,5,6];
var p1 = _.first(ar, 4);
var p2 = _.rest(ar, 4);