原文鏈接:https://blog.csdn.net/u010323023/article/details/52700770
在JavaScript中,除了Object之外,Array類型恐怕就是最常用的類型了。與其他語言的數(shù)組有著很大的區(qū)別,JavaScript中的Array非常靈活。今天我就來總結(jié)了一下JavaScript中Array刪除的方法。大致的分類可以分為如下幾類:
1、length
2、delete
3、棧方法
4、隊(duì)列方法
5、操作方法
6、迭代方法
7、原型方法
下面我對上面說的方法做一一的舉例和解釋。
一、length
JavaScript中Array的length屬性非常有特點(diǎn)一一它不是只讀的。因此,通過設(shè)置這個(gè)屬性可以從數(shù)組的末尾移除項(xiàng)或添加新項(xiàng),請看下面例子:
1 var colors = ["red", "blue", "grey"]; //創(chuàng)建一個(gè)包含3個(gè)字符串的數(shù)組2 colors.length = 2;3 console.log(colors[2]); //undefined
二、delete關(guān)鍵字
1 var arr = [1, 2, 3, 4];2 delete arr[0];3 4 console.log(arr); //[undefined, 2, 3, 4]
可以看出來,delete刪除之后數(shù)組長度不變,只是被刪除元素被置為undefined了。
三、棧方法
1 var colors = ["red", "blue", "grey"];2 var item = colors.pop();3 console.log(item); //"grey"4 console.log(colors.length); //2
可以看出,在調(diào)用Pop方法時(shí),數(shù)組返回最后一項(xiàng),即”grey”,數(shù)組的元素也僅剩兩項(xiàng)。
四、隊(duì)列方法
隊(duì)列數(shù)據(jù)結(jié)構(gòu)的訪問規(guī)則是FIFO(先進(jìn)先出),隊(duì)列在列表的末端添加項(xiàng),從列表的前端移除項(xiàng),使用shift方法,它能夠移除數(shù)組中的第一個(gè)項(xiàng)并返回該項(xiàng),并且數(shù)組的長度減1。
1 var colors = ["red", "blue", "grey"];2 var item = colors.shift();3 console.log(item); //"red"4 console.log(colors.length); //2
五、操作方法
splice()恐怕要算最強(qiáng)大的數(shù)組方法了,他的用法有很多種,在此只介紹刪除數(shù)組元素的方法。在刪除數(shù)組元素的時(shí)候,它可以刪除任意數(shù)量的項(xiàng),只需要指定2個(gè)參數(shù):要刪除的第一項(xiàng)的位置和要刪除的項(xiàng)數(shù),例如splice(0, 2)會刪除數(shù)組中的前兩項(xiàng)。
1 var colors = ["red", "blue", "grey"];2 var item = colors.splice(0, 1);3 console.log(item); //"red"4 console.log(colors); //["blue", "grey"]
六、迭代方法
所謂的迭代方法就是用循環(huán)迭代數(shù)組元素發(fā)現(xiàn)符合要刪除的項(xiàng)則刪除,用的最多的地方可能是數(shù)組中的元素為對象的時(shí)候,根據(jù)對象的屬性例如ID等等來刪除數(shù)組元素。下面介紹兩種方法:
第一種用最常見的ForEach循環(huán)來對比元素找到之后將其刪除:
var colors = ["red", "blue", "grey"];colors.forEach(function(item, index, arr) { if(item == "red") { arr.splice(index, 1); }});
第二種我們用循環(huán)中的filter方法:
1 var colors = ["red", "blue", "grey"];2 3 colors = colors.filter(function(item) {4 return item != "red"5 });6 7 console.log(colors); //["blue", "grey"]
代碼很簡單,找出元素不是”red”的項(xiàng)數(shù)返回給colors(其實(shí)是得到了一個(gè)新的數(shù)組),從而達(dá)到刪除的作用。
七、原型方法
通過在Array的原型上添加方法來達(dá)到刪除的目的:
1 Array.prototype.remove = function(dx) { 2 3 if(isNaN(dx) || dx > this.length){ 4 return false; 5 } 6 7 for(var i = 0,n = 0;i < this.length; i++) { 8 if(this[i] != this[dx]) { 9 this[n++] = this[i];10 }11 }12 this.length -= 1;13 };14 15 var colors = ["red", "blue", "grey"];16 colors.remove(1);
console.log(colors); //["red", "grey"]
在此把刪除方法添加給了Array的原型對象,則在此環(huán)境中的所有Array對象都可以使用該方法。盡管可以這么做,但是我們不推薦在產(chǎn)品化的程序中來修改原生對象的原型。道理很簡單,如果因某個(gè)實(shí)現(xiàn)中缺少某個(gè)方法,就在原生對象的原型中添加這個(gè)方法,那么當(dāng)在另一個(gè)支持該方法的實(shí)現(xiàn)中運(yùn)行代碼時(shí),就可能導(dǎo)致命名沖突。而且這樣做可能會意外的導(dǎo)致重寫原生方法。