Removing elements from JavaScript arrays

后端 未结 5 2121
别跟我提以往
别跟我提以往 2021-02-10 22:31

I have the following array setup, i,e:

var myArray = new Array();

Using this array, I am creating a breadcrumb menu dynamically as the user add

5条回答
  •  不要未来只要你来
    2021-02-10 22:57

    Remove array element by position/element(Actual array modifies)

    1 - arr.splice(1, 1) -----> (index, no of elements)

    2 - arr.splice(arr.indexOf(5), 1) -----> (array.indexOf(InputValue), no of elements)

    let arr = [1,2,3,4,5];
    console.log(arr.splice(1,1));                // [2]
    console.log(arr.splice(arr.indexOf(5), 1));  // [5]
    console.log(arr);                            // [1, 3, 4]

    Remove array element by position/element(creates copy array)

    let arr2 = [10, 20, 30, 40]
    let result = arr2.filter(a=> a!==20);
    let result2 = arr2.filter(a=> a!==arr2[arr2.indexOf(30)])
    console.log(result)    // [10, 30, 40]
    console.log(result2)   // [10, 20, 40]

提交回复
热议问题