JavaScript 数组:获取“范围";项目

2022-01-24 00:00:00 arrays range ruby javascript

在 JavaScript 中是否有 ruby​​ 的 array[n..m] 等价物?

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

例如:

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

推荐答案

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

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']

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

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.

相关文章