Javascript 从 N 到最后一个元素的切片数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14395050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:37:48  来源:igfitidea点击:

slice array from N to last element

javascript

提问by evfwcqcg

How to make this transformation?

如何进行这种转变?

["a","b","c","d","e"] // => ["c", "d", "e"]

I was thinking that slicecan do this, but..

我以为slice可以做到这一点,但是..

["a","b","c","d","e"].slice(2,-1) // [ 'c', 'd' ]
["a","b","c","d","e"].slice(2,0)  // []

回答by Tim S.

Don't use the second argument:

不要使用第二个参数:

Array.slice(2);


https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice

If end is omitted, slice extracts to the end of the sequence.

如果省略 end,则切片提取到序列的末尾。

回答by Connor Goddard

An important consideration relating to the answer by @insomniac is that spliceand sliceare two completely different functions, with the main difference being:

与@insomniac 的答案相关的一个重要考虑因素是spliceslice是两个完全不同的函数,主要区别在于:

  • splicemanipulates the original array.
  • slicereturns a sub-set of the original array, with the original array remaining untouched.
  • splice操作原始数组。
  • slice返回原始数组的子集,原始数组保持不变。

See: http://ariya.ofilabs.com/2014/02/javascript-array-slice-vs-splice.htmlfor more information.

有关更多信息,请参阅:http: //ariya.ofilabs.com/2014/02/javascript-array-slice-vs-splice.html

回答by insomiac

Just give the starting index as you want rest of the data from the array..

只需给出起始索引,因为您需要数组中的其余数据。

["a","b","c","d","e"].splice(2) => ["c", "d", "e"]

回答by jayvatar

Slice ends at the specified end argument but does not include it. If you want to include it you have to specify the last index as the length of the array (5 in this case) as opposed to the end index (-1) etc.

切片在指定的结束参数处结束,但不包括它。如果要包含它,则必须将最后一个索引指定为数组的长度(在本例中为 5),而不是结束索引 (-1) 等。

["a","b","c","d","e"].slice(2,5) // = ['c','d','e']

["a","b","c","d","e"].slice(2,5) // = ['c','d','e']

回答by Alok Ranjan

var arr = ["a", "b", "c", "d", "e"];
arr.splice(0,2);
console.log(arr);
请使用上面的代码。可能是你需要的。