Js之怎么移除Array数组中指定元素

前端开发   发布日期:2023年07月30日   浏览次数:201

这篇文章主要介绍“Js之怎么移除Array数组中指定元素”,在日常操作中,相信很多人在Js之怎么移除Array数组中指定元素问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Js之怎么移除Array数组中指定元素”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

    Js 移除Array数组中指定元素

    首先需要找到元素的下标:

    var array = [0,1,2,3,4,5];
    var index = array.indexOf(5);

    使用splice函数进行移除:

    if (index > -1) {
        array.splice(index, 1);
    }
    • indexOf()
      方法可返回某个指定的字符串值在字符串中首次出现的位置。
    • splice
      函数的第二个参数指删除的数目。
    • splice
      直接修改原数组,并把删除的所有元素以另一个新数组的方式返回。

    Js 数组删除元素 避坑

    length

    JavaScript中Array的length属性非常有特点一一它不是只读的。因此,通过设置这个属性可以从数组的末尾移除项或添加新项,请看下面例子:

    var colors = ["red", "blue", "grey"];   //创建一个包含3个字符串的数组
    colors.length = 2;
    console.log(colors[2]);  //undefined

    delete

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

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

    栈方法

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

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

    队列方法

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

    队列数据结构的访问规则是FIFO(先进先出),队列在列表的末端添加项,从列表的前端移除项,使用shift方法,它能够移除数组中的第一个项并返回该项,并且数组的长度减1。

    操作方法

    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"]

    原型方法

    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"];
    colors.remove(1);
    console.log(colors);    //["red", "grey"]

    在此把删除方法添加给了Array的原型对象,则在此环境中的所有Array对象都可以使用该方法。

    尽管可以这么做,但是我们不推荐在产品化的程序中来修改原生对象的原型。道理很简单,如果因某个实现中缺少某个方法,就在原生对象的原型中添加这个方法,那么当在另一个支持该方法的实现中运行代码时,就可能导致命名冲突。而且这样做可能会意外的导致重写原生方法。

    以上就是Js之怎么移除Array数组中指定元素的详细内容,更多关于Js之怎么移除Array数组中指定元素的资料请关注九品源码其它相关文章!