JavaScript take part of an array

How can I create a new array that contains all elements numbered nth to (n+k)th from an old array?


Solution 1:

You want the slice method.

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

Solution 2:

i think the slice method will do what you want.

arrayObject.slice(start,end)

Solution 3:

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