Js在Array數組中按指定位置刪除或添加元素對象


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方法,簡介如下:

資源搜索網站大全 https://www.renrenfan.com.cn 廣州VI設計公司https://www.houdianzi.com

slice簡介

slice() 方法可從已有的數組中返回選定的元素。 返回一個新數組,不修改原有數組。

arrayObject.slice(start,end)

參數描述

start 必需。規定從何處開始選取。如果是負數,那么它規定從數組尾部開始算起的位置。也就是說,-1 指最后一個元素,-2 指倒數第二個元素,以此類推。

end 可選。規定從何處結束選取。該參數是數組片斷結束處的數組下標。如果沒有指定該參數,那么切分的數組包含從 start 到數組結束的所有元素。如果這個參數是負數,那么它規定的是從數組尾部開始算起的元素。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM