JavaScript 数组:获取“范围”内的元素

104

在JavaScript中是否有与Ruby的array[n..m]相等的功能?

例如:

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

3
是的,CoffeeScript!全新升级的范围、切片、插入和循环语法 - Lance
4个回答

179

使用array.slice(begin [, end]) 函数。

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

最后一个索引不包括在内;为了模仿Ruby的行为,你需要增加end值。所以我想slice更像是Ruby中的a[m...n]


11
The last index is non-inclusive. - pasx

23

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

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

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

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

这是W3 Schools参考 链接


7
请问是否需要翻译以下内容?"How about linking to Mozilla's javascript reference, which is far more informative and much better written than the W3 schools site (which has nothing to do with the W3C)? https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice" - Bobby Jack

10

1
实际上应该是a.slice(0, 3)。在JavaScript中,slice方法不包括结束索引。 - Anurag

4
Ruby和Javascript都有一个slice方法,但要注意,在Ruby中slice的第二个参数是长度,而在JavaScript中它是最后一个元素的索引:
var shortArray = array.slice(start, end);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接