Javascript filter function polyfill

Javascript filter function polyfill

本文关键字:polyfill function filter Javascript      更新时间:2023-09-26

我不明白为什么检查对应于第 if (i in t) 行 - 第 18 行放置在过滤器函数 polyfill 中:

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;
  };
}

这是为了避免稀疏数组中尚未定义的元素。请参阅以下示例,

var array = [];
array[3] = 10;
console.log(array.length);
// 4

因此,数组的长度为 4,但只定义了索引 3 处的元素,所有其他元素尚未定义。所以,如果你这样做

for (var i = 0; i < array.length; i += 1) {
    console.log(i, array[i]);
}

你会得到

0 undefined
1 undefined
2 undefined
3 10

数组是特殊的 JavaScript 对象。索引只是数组对象中的属性。 每当使用不在数组中的索引扩展数组对象时,length 属性将在内部进行调整。在这种情况下,数组对象中只有一个属性,名称3定义。但是我们正在尝试访问从 0 到 3 的元素。因此,它为数组对象中尚不存在的所有索引返回undefined

为了避免这种情况,我们正在检查当前索引是否真的在数组对象中定义,if语句。

for (var i = 0; i < array.length; i += 1) {
    if (i in array) {
        console.log(i, array[i]);
    }
}

会打印

3 10

这是因为 JavaScript 数组可能存在间隙。

例如,请考虑以下事项:

var a = ["hello", "howdy", "welcome"];
delete greetings[1];
"0" in a; // true
"1" in a; // false
"2" in a; // true
Array.prototype.myFilter = function(callBack) {
 let newArray = [];
 for (let i = 0; i < this.length; i++) {
  let result = callBack(this[i], i, this);
    if (result) {
     newArray.push(this[i]);
    }
}
return newArray;

IN 是一个保留关键字,可用于 for 和 if 语句。

18th line they are doing exist check

参考这个点与内。

创建自己的filter()方法

Array.prototype.newFilter = function(func){
  let filtered = [], n = this.length;
  
  for(let i = 0; i<n; i++) {
   if(func(this[i],i,this)) 
    filtered.push(this[i]);
  }
  return filtered;
}
let result = [1,2,3,4,5,6,7].newFilter(item => item > 4);
console.log(result);

Array.prototype.myFilter = function(callBackFn) {
    let res = [];
    if (!Array.isArray(this)) {
        throw new Error(`${this} is not a function`);
    }
    for (let i = 0; i<this.length; i++) {
        if (callBackFn(this[i], i, this)) {
            res.push(this[i])
        }
    }
    return res
}