Javascript Array:获取项目的“范围”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3580239/
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-23 05:17:16  来源:igfitidea点击:

Javascript Array: get 'range' of items

javascriptrubyarraysrange

提问by shdev

Is there an equivalent for ruby's array[n..m] in Javascript ?

Javascript 中 ruby​​ 的数组[n..m] 是否有等价物?

For example:

例如:

>> a = ['a','b','c','d','e','f','g']
>> a[0..2]
=> ['a','b','c']

Thanks

谢谢

回答by Vivin Paliath

Use the array.slice(begin [, end])function.

使用该array.slice(begin [, end])功能。

var a = ['a','b','c','d','e','f','g'];
var sliced = a.slice(0, 3); //will contain ['a', 'b', 'c']

The last index is non-inclusive;to mimic ruby's behavior you have to increment the endvalue. So I guess slicebehaves more like a[m...n]in ruby.

最后一个索引是非包含的;要模仿 ruby​​ 的行为,您必须增加该end值。所以我猜它的slice行为更像是a[m...n]在 ruby​​ 中。

回答by Robert

a.slice(0, 3)Would be the equivalent of your function in your example.

a.slice(0, 3)将相当于您的示例中的功能。

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

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

回答by David Hoerster

The second argument in sliceis optional, too:

in 中的第二个参数slice也是可选的:

var fruits = ['apple','banana','peach','plum','pear'];
var slice1 = fruits.slice(1, 3);  //banana, peach, plum
var slice2 = fruits.slice(3);  //plum, pear

You can also pass a negative number, which selects from the end of the array:

您还可以传递一个负数,它从数组的末尾选择:

var slice3 = fruits.slice(-3);  //peach, plum, pear

Here's the W3 Schools reference link.

这是 W3 学校参考链接

回答by Douglas

Ruby and Javascript both have a slice method, but watch out that the second argument to slice in Ruby is the length, but in JavaScript it is the index of the last element:

Ruby 和 Javascript 都有slice 方法,但要注意 Ruby 中 slice 的第二个参数是长度,但在 JavaScript 中它是最后一个元素的索引:

var shortArray = array.slice(start, end);