Javascript数组:获取'范围'的项目

问题描述:

Javascript中是否有等效的ruby数组[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(开始[,结束]) 功能。

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.