JavaScript 在参数中传递新数组

JavaScript pass new array in argument

有没有一种方法(就像我们在 C# generics/linq list.take... 中那样)可以在调用函数时在参数中获取数组元素的范围,而不必创建一个新数组?

//a simple array with some elements
myArray; 
//just to show what I mean...pass the first five elemtns of array to the function
doSomethingWithArray(myArray[0,4]); 


function doSomethingWithArray(items) {
   //do stuff
}

听起来您可能正在寻找 slice

doSomethingWithArray(myArray.slice(0, 4))

Slice 采用 startend 参数以及 returns 数组中属于该范围内的项目的 浅拷贝 。如果你想改变数组,你可以考虑 splice.

注意end索引是不包含,即myArray.slice(0,4),例子中,returns只包含范围内的元素[0 .. 3].