js怎么删除数组中指定元素? 您所在的位置:网站首页 js数组删除指定位置元素 js怎么删除数组中指定元素?

js怎么删除数组中指定元素?

#js怎么删除数组中指定元素?| 来源: 网络整理| 查看: 265

javascript删除数组中指定元素

splice()函数

splice()恐怕要算最强大的数组方法了,他的用法有很多种,在此只介绍删除数组元素的方法。在删除数组元素的时候,它可以删除任意数量的项,只需要指定2个参数:要删除的第一项的位置和要删除的项数,例如splice(0, 2)会删除数组中的前两项。

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

迭代方法删除数组中指定元素

所谓的迭代方法就是用循环迭代数组元素发现符合要删除的项则删除,用的最多的地方可能是数组中的元素为对象的时候,根据对象的属性例如ID等等来删除数组元素。下面介绍两种方法:

第一种用最常见的ForEach循环来对比元素找到之后将其删除:

var colors = ["red", "blue", "grey"]; colors.forEach(function(item, index, arr) { if(item == "red") { arr.splice(index, 1); } });

第二种我们用循环中的filter方法:

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

代码很简单,找出元素不是”red”的项数返回给colors(其实是得到了一个新的数组),从而达到删除的作用。

delete关键字删除数组中指定元素

var arr = [1, 2, 3, 4]; delete arr[0]; console.log(arr); //[undefined, 2, 3, 4]

可以看出来,delete删除之后数组长度不变,只是被删除元素被置为undefined了。

扩展资料:

pop() 方法

pop() 方法用于删除并返回数组的最后一个元素。

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

可以看出,在调用Pop方法时,数组返回最后一项,即”grey”,数组的元素也仅剩两项。

shift() 方法

shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。

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

以上就是js怎么删除数组中指定元素?的详细内容,更多请关注html中文网其它相关文章!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有