Deleting array elements in JavaScript - delete vs splice

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

提交回复
热议问题