这是我写的,要实现的就是对数组中的非稀疏元素进行操作
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
自己的一点见解:
if (this == null) {
用来判断作用对象是否为null 或 undefined , 这里用了 双等 , 作用是在比较之前会默认进行类型转换,比如把 '',undefined,0,false 都给转转化成undefined , 作用是判断、过滤作用对象。
var target = '' || false || 0 || undefined || null ;
if(target == null) {
console.log('target is undefined')
}
T = thisArg;
这个东西在MDN里有说,他是在forEach执行callback时的this值,比如:
var array = [1,2,3];
var result = [];
array.forEach(function(i){
this.push(i*i);
},result); // result ==> [1, 4, 9]
或者在reduce里,
[1,2,3].reduce(
function(p,v){
return p + v
}) // 6
[1,2,3].reduce(
function(p,v){
return p + v
},10) // 16