slice array from N to last element

前端 未结 7 2014
你的背包
你的背包 2020-12-29 01:11

How to make this transformation?

[\"a\",\"b\",\"c\",\"d\",\"e\"] // => [\"c\", \"d\", \"e\"]

I was thinking that slice can

相关标签:
7条回答
  • 2020-12-29 01:39

    Slice ends at the specified end argument but does not include it. If you want to include it you have to specify the last index as the length of the array (5 in this case) as opposed to the end index (-1) etc.

    ["a","b","c","d","e"].slice(2,5) 
    // = ['c','d','e']
    
    0 讨论(0)
  • An important consideration relating to the answer by @insomniac is that splice and slice are two completely different functions, with the main difference being:

    • splice manipulates the original array.
    • slice returns a sub-set of the original array, with the original array remaining untouched.

    See: http://ariya.ofilabs.com/2014/02/javascript-array-slice-vs-splice.html for more information.

    0 讨论(0)
  • 2020-12-29 01:47

    Don't use the second argument:

    Array.slice(2);
    

    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice

    If end is omitted, slice extracts to the end of the sequence.

    0 讨论(0)
  • 2020-12-29 01:52

    Just give the starting index as you want rest of the data from the array..

    ["a","b","c","d","e"].splice(2) => ["c", "d", "e"]
    
    0 讨论(0)
  • 2020-12-29 01:58

    var arr = ["a", "b", "c", "d", "e"];
    arr.splice(0,2);
    console.log(arr);
    Please use above code. May be this you need.

    0 讨论(0)
  • 2020-12-29 02:00

    You must add a "-" before n If the index is negative, the end indicates an offset from the end.

    function getTail(arr, n) {
    return arr.slice(-n);
    }
    
    0 讨论(0)
提交回复
热议问题