Deleting array elements in JavaScript - delete vs splice

后端 未结 27 3681
予麋鹿
予麋鹿 2020-11-21 05:31

What is the difference between using the delete operator on the array element as opposed to using the Array.splice method?

For example:

myArray = [\         


        
27条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 06:11

    I stumbled onto this question while trying to understand how to remove every occurrence of an element from an Array. Here's a comparison of splice and delete for removing every 'c' from the items Array.

    var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
    
    while (items.indexOf('c') !== -1) {
      items.splice(items.indexOf('c'), 1);
    }
    
    console.log(items); // ["a", "b", "d", "a", "b", "d"]
    
    items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
    
    while (items.indexOf('c') !== -1) {
      delete items[items.indexOf('c')];
    }
    
    console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
    ​
    

提交回复
热议问题