87,996
社区成员




if (!Object.prototype.forEach) {
Object.prototype.forEach = function(fn) {
if ({}.toString.call(this) != "[object Object]") {
throw new TypeError();
}
if (typeof fn != "function") {
throw new TypeError();
}
for (var key in this) {
if(key in this){
fn.call(this, this[key], key, this);
//执行回调函数,并传入参数:值、索引、对象
}
}
}
}
var obj = {"a": 1,"b": 2};
obj.forEach(function(a,b,c){
console.log(a,b,c);
/*
1 "a" Object {a: 1, b: 2}
2 "b" Object {a: 1, b: 2}
-----------------------------------------------------------
//为什么会打印出函数体来?
function (fn) {
if ({}.toString.call(this) != "[object Object]") {
throw new TypeError();
}
if (typeof fn != "function") {
throw new TypeError();
}
for (var key in this) {
if(key in… "forEach" Object {a: 1, b: 2}
*/
})
for (var key in this) {
if(this.hasOwnProperty(key)){
fn.call(this, this[key], key, this);
//执行回调函数,并传入参数:值、索引、对象
}
}