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

下面小编就为大家带来一篇js中数组插入、删除元素操作的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

实例如下:

 /* * 删除数组元素: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中数组插入、删除元素操作的方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » JavaScript 教程