Deleting array elements in JavaScript - delete vs splice

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

    you can use something like this

    var my_array = [1,2,3,4,5,6];
    delete my_array[4];
    console.log(my_array.filter(function(a){return typeof a !== 'undefined';})); // [1,2,3,4,6]

    0 讨论(0)
  • 2020-11-21 06:15

    For those who wants to use Lodash can use: myArray = _.without(myArray, itemToRemove)

    Or as I use in Angular2

    import { without } from 'lodash';
    ...
    myArray = without(myArray, itemToRemove);
    ...
    
    0 讨论(0)
  • 2020-11-21 06:18

    delete: delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:

    splice: actually removes the element, reindexes the array, and changes its length.

    Delete element from last

    arrName.pop();
    

    Delete element from first

    arrName.shift();
    

    Delete from middle

    arrName.splice(starting index,number of element you wnt to delete);
    
    Ex: arrName.splice(1,1);
    

    Delete one element from last

    arrName.splice(-1);
    

    Delete by using array index number

     delete arrName[1];
    
    0 讨论(0)
  • 2020-11-21 06:19

    If the desired element to delete is in the middle (say we want to delete 'c', which its index is 1), you can use:

    var arr = ['a','b','c'];
    var indexToDelete = 1;
    var newArray = arr.slice(0,indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))
    
    0 讨论(0)
  • 2020-11-21 06:20

    Currently there are two ways to do this

    1. using splice()

      arrayObject.splice(index, 1);

    2. using delete

      delete arrayObject[index];

    But I always suggest to use splice for array objects and delete for object attributes because delete does not update array length.

    0 讨论(0)
  • 2020-11-21 06:21

    Array.remove() Method

    John Resig, creator of jQuery created a very handy Array.remove method that I always use it in my projects.

    // Array Remove - By John Resig (MIT Licensed)
    Array.prototype.remove = function(from, to) {
      var rest = this.slice((to || from) + 1 || this.length);
      this.length = from < 0 ? this.length + from : from;
      return this.push.apply(this, rest);
    };
    

    and here's some examples of how it could be used:

    // Remove the second item from the array
    array.remove(1);
    // Remove the second-to-last item from the array
    array.remove(-2);
    // Remove the second and third items from the array
    array.remove(1,2);
    // Remove the last and second-to-last items from the array
    array.remove(-2,-1);
    

    John's website

    0 讨论(0)
提交回复
热议问题