zoukankan      html  css  js  c++  java
  • 数组删除元素

    一、length

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

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

    二、delete关键字

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

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

    三、pop

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

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

    四、shift方法,它能够移除数组中的第一个项并返回该项,并且数组的长度减1。

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

    五、splice操作方法 

    在删除数组元素的时候,它可以删除任意数量的项,只需要指定2个参数:要删除的第一项的位置和要删除的项数,例如splice(0, 2)会删除数组中的前两项。

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

    六、filter方法:

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

    1 var colors = ["red", "blue", "grey"];
    2 
    3 colors = colors.filter(function(item) {
    4     return item != "red"
    5 });
    6 
    7 console.log(colors);    //["blue", "grey"]

    七、ForEach循环来对比元素找到之后将其删除:

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

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

    八、在原型上添加方法删除:

     1 Array.prototype.remove = function(dx) {
     2 
     3     if(isNaN(dx) || dx > this.length){
     4         return false;
     5     }
     6 
     7     for(var i = 0,n = 0;i < this.length; i++) {
     8         if(this[i] != this[dx]) {
     9             this[n++] = this[i];
    10         }
    11     }
    12     this.length -= 1;
    13 };
    14 
    15 var colors = ["red", "blue", "grey"];
    16 colors.remove(1);
      console.log(colors); //["red", "grey"]
  • 相关阅读:
    Serverless:这真的是未来吗?(二)
    阿里云 EDAS 3.0 助力唱鸭提升微服务幸福感
    520,一份给程序员的“硬核”脱单秘籍
    稳定性之故障应急处理流程
    殷浩详解DDD:领域层设计规范
    Vineyard 加入 CNCF Sandbox,将继续瞄准云原生大数据分析领域
    【开通指南】 实时计算 Flink 全托管版本
    【HTML】html5 canvas全屏烟花动画特效
    【HTML】中国天气天气插件调用
    【Python】求n!
  • 原文地址:https://www.cnblogs.com/ll15888/p/11555052.html
Copyright © 2011-2022 走看看