前端基础知识 (五)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"]
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值