JavaScript成为数组的一部分


70

如何创建一个新数组,其中包含旧数组中编号为n到(n + k)的所有元素?

Answers:



14

我认为slice方法将做您想要的。

arrayObject.slice(start,end)

3

Slice会创建浅表副本,因此不会创建精确副本。例如,考虑以下内容:

var foo = [[1], [2], [3]];
var bar = foo.slice(1, 3);
console.log(bar); // = [[2], [3]]
bar[0][0] = 4;
console.log(foo); // [[1], [4], [3]]
console.log(bar); // [[4], [3]]

1

原型解决方案:

Array.prototype.take = function (count) {
    return this.slice(0, count);
}

0

假设我们有一个包含六个对象的数组,并且我们想要获得前三个对象。

解决方案:

var arr = [{num:1}, {num:2}, {num:3}, {num:4}, {num:5}, {num:6}];
arr.slice(0, 3); //will return first three elements
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.