Removing elements from JavaScript arrays

后端 未结 5 2060
别跟我提以往
别跟我提以往 2021-02-10 22:31

I have the following array setup, i,e:

var myArray = new Array();

Using this array, I am creating a breadcrumb menu dynamically as the user add

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-10 22:40

    I like this implementation of Array.remove, it basically abstracts the use of the splice function:

    // 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);
    };
    

    Usage:

    // 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);
    

提交回复
热议问题