admin管理员组文章数量:1134246
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']
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']
Share
Improve this question
edited May 3, 2021 at 22:42
A-Sharabiani
19.3k21 gold badges125 silver badges137 bronze badges
asked Aug 26, 2010 at 23:08
shdevshdev
1,9854 gold badges17 silver badges18 bronze badges
1
- 3 yes, coffeescript! New-and-improved range, slice, splice and loop syntax. – Lance Pollard Commented May 18, 2011 at 23:02
4 Answers
Reset to default 193Use 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.
The second argument in slice
is optional, too:
var fruits = ['apple','banana','peach','plum','pear'];
var slice1 = fruits.slice(1, 3); //banana, peach
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.
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
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);
本文标签: rubyJavaScript Array get quotrangequot of itemsStack Overflow
版权声明:本文标题:ruby - JavaScript Array: get "range" of items - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736854032a1955634.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论