for循环删除数组时的问题

来源:互联网 发布:非线性优化 编辑:程序博客网 时间:2024/04/27 17:17

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

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被重写而出现判断不准确的情况。

原创粉丝点击