Javascript Array: get 'range' of items

喜你入骨 提交于 2019-11-26 18:19:43

问题


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

For example:

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

Thanks


回答1:


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

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 end value. So I guess slice behaves more like a[m...n] in ruby.




回答2:


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

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




回答3:


The second argument in slice is optional, too:

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.




回答4:


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:

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


来源:https://stackoverflow.com/questions/3580239/javascript-array-get-range-of-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!