remove array value after index

This question already has an answer here:

  • How do I remove a particular element from an array in JavaScript? 63 answers

  • You need to use slice(0,3) to slice out between indexes 0 and 3, obtaining indexes 0,1,2. That's [5,10,15] .


    You seem to just want to truncate the array. The simplest way is to set its length :

    array.length = 3;
    

    If you were doing that based on an index (say, index = 2 ), you'd add one to get the length, as arrays are 0-based:

    array.length = index + 1;
    

    If you want to get a copy a subset of elements as a new array, you would indeed use slice :

    var new_array = array.slice(0, 3);
    

    Live example of truncation:

    var array = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60];
    snippet.log("Before: " + array.join(", "));
    array.length = 3;
    snippet.log("After: " + array.join(", "));
    <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
    链接地址: http://www.djcxy.com/p/19034.html

    上一篇: 获取数组中的所有唯一值(删除重复项)

    下一篇: 索引后删除数组值