Method of Array Insert and Delete Element Operation in js

  • 2021-07-21 07:08:53
  • OfStack

Examples are as follows:


/*
  *  Delete Array Elements :Array.removeArr(index)
  */
  Array.prototype.removeArr = function (index) {
    if (isNaN(index) || index>= this.length) { return false; }
    this.splice(index, 1);
  }
  /*
  *  Insert an array element :Array.insertArr(dx)
  */
  Array.prototype.insertArr = function (index, item) {
    this.splice(index, 0, item);
  };

Through the above function, you can handle the actions of moving up and down


if (tag == 2) { // Move up 
      if (targeitemindex == 0) return; // Top 
      rows.removeArr(targeitemindex); // Removes the specified object, reducing the length of the original object 1 A 
      rows.insertArr(targeitemindex - 1, targetitem);
    } else if (tag == 3) { // Move down 
      if (targeitemindex == len - 1) return; // Bottom 
      rows.removeArr(targeitemindex); // Removes the specified object, reducing the length of the original object 1 A 
      rows.insertArr(targeitemindex + 1, targetitem);
    }

Definition and usage

The splice () method adds/deletes items to/from the array and returns the deleted items.

Note: This method changes the original array.

Grammar


arrayObject.splice(index,howmany,item1,.....,itemX)

参数 描述
index 必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。
howmany 必需。要删除的项目数量。如果设置为 0,则不会删除项目。
item1, ..., itemX 可选。向数组添加的新项目。

Return value

类型 描述
Array 包含被删除项目的新数组,如果有的话。

Description

The splice () method deletes zero or more elements starting at index and replaces those deleted elements with one or more values declared in the parameter list.

If an element is deleted from arrayObject, an array containing the deleted element is returned.


Related articles: