Javascript Array: get 'range' of items

后端 未结 4 2110
谎友^
谎友^ 2020-11-29 07:54

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]         


        
4条回答
  •  情书的邮戳
    2020-11-29 08:28

    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.

提交回复
热议问题