当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js中数组插入、删除元素操作的方法

js中数组插入、删除元素操作的方法

2019年03月25日  | 移动技术网IT编程  | 我要评论

实例如下:

/*
  * 删除数组元素:array.removearr(index)
  */
  array.prototype.removearr = function (index) {
    if (isnan(index) || index>= this.length) { return false; }
    this.splice(index, 1);
  }
  /*
  * 插入数组元素:array.insertarr(dx)
  */
  array.prototype.insertarr = function (index, item) {
    this.splice(index, 0, item);
  };

通过上面的函数,可以处理上移和下移的动作

if (tag == 2) { //上移
      if (targeitemindex == 0) return; //顶部
      rows.removearr(targeitemindex); //移除指定对象,原对象长度减少一个
      rows.insertarr(targeitemindex - 1, targetitem);
    } else if (tag == 3) { //下移
      if (targeitemindex == len - 1) return; //底部
      rows.removearr(targeitemindex); //移除指定对象,原对象长度减少一个
      rows.insertarr(targeitemindex + 1, targetitem);
    }

定义和用法

splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。

注释:该方法会改变原始数组。

语法

arrayobject.splice(index,howmany,item1,.....,itemx)

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

返回值

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

说明

splice() 方法可删除从 index 处开始的零个或多个元素,并且用参数列表中声明的一个或多个值来替换那些被删除的元素。

如果从 arrayobject 中删除了元素,则返回的是含有被删除的元素的数组。

以上这篇js中数组插入、删除元素操作的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网