41

JavaScript在Array数组中按指定位置删除或添加元素对象

 4 years ago
source link: http://ourjs.com/detail/k34hhj5bjiqq
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JavaScript的数据中可通过splice/slice在指定位置添加或删除元素。另外还有slice、delete等方法实现。

splice简介

splice方法向/从数组中添加/删除项目,然后返回被删除的项目。 该方法会改变原始数组。

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

参数 描述

index 必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。

howmany 必需。要删除的项目数量。如果设置为 0,则不会删除项目。

item1, ..., itemX 可选。向数组添加的新项目。

使用示例

删除第3个元素

var arr = [1, 2, 3, 4, 5];
arr.splice(2, 1);
console.log(arr) //[1, 2, 4, 5]

删除开始的3个元素

var arr = [1, 2, 3, 4, 5];
arr.splice(0, 3);
console.log(arr); //[4, 5]

在第2个元素后,添加新数字 9

var arr = [1, 2, 3, 4, 5];
arr.splice(2, 0, 9);
console.log(arr) //[1, 2, 9, 3, 4, 5]

Array.insert 添加

借助splice可以在array上面添加一个原生的insert方法,直接操作数组:

Array.prototype.insert = function(index) {
 index = Math.min(index, this.length);
 arguments.length > 1
 && this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
 && this.insert.apply(this, arguments);
 return this;
};

使用示例

var arr = [1, 2, 3, 4, 5];
arr.insert(2, -1, -2, -3);
console.log(arr); // [1, 2, -1, -2, -3, 3, 4, 5]

Array.remove 删除

也可以用slice在array上面添加一个原生的remove方法

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

使用,删除第3个元素

var arr = [1, 2, 3, 4, 5];
arr.remove(2); //第3个元素索引是2
console.log(arr); //[1, 2, 4, 5]

这里使用了slice方法,简介如下:

slice简介

slice() 方法可从已有的数组中返回选定的元素。 返回一个新数组,不修改原有数组。

arrayObject.slice(start,end)

参数描述

start 必需。规定从何处开始选取。如果是负数,那么它规定从数组尾部开始算起的位置。也就是说,-1 指最后一个元素,-2 指倒数第二个元素,以此类推。

end 可选。规定从何处结束选取。该参数是数组片断结束处的数组下标。如果没有指定该参数,那么切分的数组包含从 start 到数组结束的所有元素。如果这个参数是负数,那么它规定的是从数组尾部开始算起的元素。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK