Javascript Array: get 'range' of items

后端 未结 4 2103
谎友^
谎友^ 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:21

    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.

提交回复
热议问题