这是我写的,要实现的就是对数组中的非稀疏元素进行操作
Array.prototype.foreach = function(callback){
var a = this;
for(var i = 0;i<this.length;i++){
if(!(i in a)) continue;
callback(a[i],i,a);
}
}
这是ES5源码
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
Array.prototype.forEach = function(callback, thisArg) {
var T, k;
if (this == null) { //难道Array可能为null??什么情况下?
throw new TypeError(' this is null or not defined');
}
var O = Object(this); //这有什么用?
var len = O.length >>> 0; //这有什么用?
if (typeof callback !== "function") {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = thisArg; //thisArg有什么用?
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
问题已写在注释中,求指导。
关于第三个问:length >>> 0 ,提供一个参考链接
简单说下
第一个疑问:如果我这样呢
[].forEach.call(null, function() {})
第二个疑问:强制转换为Object,为了统一处理循环不报错,也可以处理类似
[].forEach.call("123", function() {})
第三个疑问:你可以理解为把length转换为数字,如果length是字符串,也可以转换为数字
第四个疑问,如楼上所说,为了改变callback的this