前端基础知识 (五)JS删除数组元素的方法

一、length属性

JS 中Array的length长度非常有特点,他不是只读的,因此可以设置。
var colors = ["red","blue","grey"];
colors.length = 2;
console.log(colors[2])  // undefined
console.log(colors) // ["red", "blue"]

二、delete关键字

注意 长度不会变

var colors = ["red","blue","grey"];
delete colors[0];
console.log(colors[2])
console.log(colors) // [undefined, "red", "blue"]

三、pop()栈方法

用于弹出并返回数组的最后一组元素

var colors = ["red","blue","grey"];
var color = colors.pop();
console.log(color); // grey
console.log(colors.length) // 2

四、shift()队列方法

用于弹出并返回数组的第一个元素

五、splice()操作方法

var colors = ["red","blue","grey"];
var color = colors.splice(0,1);
console.log(color); // red
console.log(colors) // ["blue", "grey"]

语法: arrayobject.splice(index, howmany, item1, item2 …)
index:规定添加/删除的下标位置
howmany:要删除的数量
item1:可选,想数组添加的新项目

六、迭代方法

(循环迭代数组元素)可配合splice()

1、用常见的forEach循环对比元素,找到之后删除

2、用循环中的filter方法

var colors = ["red","blue","grey"];
var color = colors.filter(function(item){
	return item != "red"
});
console.log(color); // ["blue", "grey"]
console.log(colors) // ["red", "blue", "grey"]

七、prototype原型方法

可以通过在Array原型上添加方法来达到删除的目的

Array.prototype.remove = function(dx) {
	if (isNaN(dx) || dx > this.length) return false;
	for (var i = 0, n = 0; i < this.length; i++) {
		if (this[i] != this[dx]) this[n++] = this[i]
	}
	this.length -= 1;
}
var colors = ["red","blue","grey"];
var color = colors.remove(1)
console.log(color); // undefined
console.log(colors) // ["red",  "grey"]

版权声明:本文为AGCA_ZXL原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。