JavaScript 数组:获取“范围”项目数
JavaScript 中是否有与 ruby 的 array[n..m]
等效的东西?
例如:
>> a = ['a','b','c','d','e','f','g']
>> a[0..2]
=> ['a','b','c']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
array.slice(begin [, end])
函数。
最后一个索引是非包含的;要模仿 ruby 的行为,您必须增加
end
值。所以我猜slice
的行为更像 ruby 中的a[m...n]
。Use the
array.slice(begin [, end])
function.The last index is non-inclusive; to mimic ruby's behavior you have to increment the
end
value. So I guessslice
behaves more likea[m...n]
in ruby.slice
中的第二个参数也是可选的:您还可以传递一个负数,该负数从数组的末尾进行选择:
这是 W3 Schools 参考 链接。
The second argument in
slice
is optional, too:You can also pass a negative number, which selects from the end of the array:
Here's the W3 Schools reference link.
a.slice(0, 3)
相当于示例中的函数。https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects /数组/切片
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 和 Javascript 都有 slice 方法,但要小心Ruby 中 slice 的第二个参数是长度,但在 JavaScript 中它是最后一个元素的索引:
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: