for循环删除数组时的问题

在删除数组元素时,会引起数组长度变换。下面的两种写法,在一次删除一个数组元素时,是没有问题的。

var fruits = ["Banana", "Orange", "Apple", "Mango"];

for (var i = fruits.length - 1; i >= 0; i--) {
    if (fruits[i] === "Apple"){
        fruits.splice(i,1);
    }
}

console.log("fruits is ",fruits);

或者

var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (var i = 0; i < fruits.length; i++) {
    if (fruits[i] === "Apple") {
        fruits.splice(i, 1);
    }
}

console.log("fruits is ", fruits);

以上代码可以遍历,完成一个元素的删除。
但是当元素有重复的时候,就需要对index进行操作:


"use strict";
var fruits = ["Banana", "Orange", "Apple", "Apple","Mango"];
for (var i = 0; i < fruits.length; i++) {
    if (fruits[i] === "Apple") {
        fruits.splice(i, 1);
        i--; // 不然会少删除Apple
    }
}

console.log("fruits is ", fruits);

js Array的原型提供的filter方法,也可删除数组中不需要的元素,但是新new了一个数组来存放需要的元素,并不改变原有数组的内容。因此不存在上面的问题。

其内部实现如下:

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /* , thisArg*/)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i];

        // NOTE: Technically this should Object.defineProperty at
        //       the next index, as push can be affected by
        //       properties on Object.prototype and Array.prototype.
        //       But that method's new, and collisions should be
        //       rare, so use the more-compatible alternative.
        if (fun.call(thisArg, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

以上代码中有 void 0的使用。 void 是 JavaScript 中非常重要的关键字,该操作符指定要计算一个表达式但是不返回值。例如,javascript:void(0), 表示一个死链接;又如

a = void(5+7);
console.log(a); // undefined

那么问题来了,为啥用void 0。非严格模式下,undefined是可以重写的,严格模式则不能重写。所以,用void 0是为了防止undefined被重写而出现判断不准确的情况。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值