Deleting array elements in JavaScript - delete vs splice

后端 未结 27 3609
予麋鹿
予麋鹿 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:08

    IndexOf accepts also a reference type. Suppose the following scenario:

    var arr = [{item: 1}, {item: 2}, {item: 3}];
    var found = find(2, 3); //pseudo code: will return [{item: 2}, {item:3}]
    var l = found.length;
    
    while(l--) {
       var index = arr.indexOf(found[l])
          arr.splice(index, 1);
       }
       
    console.log(arr.length); //1

    Differently:

    var item2 = findUnique(2); //will return {item: 2}
    var l = arr.length;
    var found = false;
      while(!found && l--) {
      found = arr[l] === item2;
    }
    
    console.log(l, arr[l]);// l is index, arr[l] is the item you look for
    

提交回复
热议问题