开发者

JavaScript take part of an array

How can I create a new array t开发者_开发问答hat contains all elements numbered nth to (n+k)th from an old array?


You want the slice method.

var newArray = oldArray.slice(n, n+k);


i think the slice method will do what you want.

arrayObject.slice(start,end)


Slice creates shallow copy, so it doesn't create an exact copy. For example, consider the following:

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]]


Prototype Solution:

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


lets say we have an array of six objects, and we want to get first three objects.

Solution :

var arr = [{num:1}, {num:2}, {num:3}, {num:4}, {num:5}, {num:6}];
arr.slice(0, 3); //will return first three elements
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜