JS操作数组的常用方式

时间:2023-03-09 17:46:12
JS操作数组的常用方式

一、JS操作数组一:删除指定的元素

  splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。

//查找指定元素下标
Array.prototype.indexOf = function(val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) return i;
}
return -1;
};
//删除指定位置的元素
Array.prototype.remove = function(val) {
var index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
}; //使用示例
var emp = ['abs','dsf','sdf','fd'];
emp.remove('fd');

二、JS操作数组二:数组的循环

//普通的for循环,但是执行效率较高
for(j = 0; j < arr.length; j++) { } //foreach循环,但是执行效率不如普通的for循环高
arr.forEach(function(e){ });