Deleting array elements in JavaScript - delete vs splice

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

    Performance

    There are already many nice answer about functional differences - so here I want to focus on performance. Today (2020.06.25) I perform tests for Chrome 83.0, Safari 13.1 and Firefox 77.0 for solutions mention in question and additionally from chosen answers

    Conclusions

    • the splice (B) solution is fast for small and big arrays
    • the delete (A) solution is fastest for big and medium fast for small arrays
    • the filter (E) solution is fastest on Chrome and Firefox for small arrays (but slowest on Safari, and slow for big arrays)
    • solution D is quite slow
    • solution C not works for big arrays in Chrome and Safari
      function C(arr, idx) {
        var rest = arr.slice(idx + 1 || arr.length);
        arr.length = idx < 0 ? arr.length + idx : idx;
        arr.push.apply(arr, rest);
        return arr;
      }
      
      
      // Crash test
      
      let arr = [...'abcdefghij'.repeat(100000)]; // 1M elements
      
      try {
       C(arr,1)
      } catch(e) {console.error(e.message)}

    Details

    I perform following tests for solutions A B C D E (my)

    • for small array (4 elements) - you can run test HERE
    • for big array (1M elements) - you can run test HERE

    function A(arr, idx) {
      delete arr[idx];
      return arr;
    }
    
    function B(arr, idx) {
      arr.splice(idx,1);
      return arr;
    }
    
    function C(arr, idx) {
      var rest = arr.slice(idx + 1 || arr.length);
      arr.length = idx < 0 ? arr.length + idx : idx;
      arr.push.apply(arr, rest);
      return arr;
    }
    
    function D(arr,idx){
        return arr.slice(0,idx).concat(arr.slice(idx + 1));
    }
    
    function E(arr,idx) {
      return arr.filter((a,i) => i !== idx);
    }
    
    myArray = ['a', 'b', 'c', 'd'];
    
    [A,B,C,D,E].map(f => console.log(`${f.name} ${JSON.stringify(f([...myArray],1))}`));
    This snippet only presents used solutions

    Example results for Chrome

提交回复
热议问题