我不能理解为什么在filter function polyfill中放置对应于第18行的if (i in t) -行的检查:
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;
};
}发布于 2014-12-29 14:41:47
它是为了避免在稀疏数组中还没有定义的元素。请参见以下示例:
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发布于 2014-12-29 14:45:21
这是因为JavaScript数组可能会有间隙。
例如,考虑以下内容:
var a = ["hello", "howdy", "welcome"];
delete greetings[1];
"0" in a; // true
"1" in a; // false
"2" in a; // true发布于 2019-08-21 20:29:24
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;https://stackoverflow.com/questions/27684465
复制相似问题