Copy codeThe Code is as follows:
Function forEach (object, block, context, fn ){
If (object = null) return;
If (! Fn ){
If (typeof object = "function" & object. call ){
// Traverse common objects
Fn = Function;
} Else if (typeof object. forEach = "function" & object. forEach! = Arguments. callee ){
// If the target has implemented the forEach method, use its own forEach method (for example, the Array object of the standard browser)
Object. forEach (block, context );
Return;
} Else if (typeof object. length = "number "){
// If it is an array object of the class or an array object of IE
_ Array_forEach (object, block, context );
Return;
}
}
_ Function_forEach (fn | Object, object, block, context );
};
Function _ Array_forEach (array, block, context ){
If (array = null) return;
Var I = 0, length = array. length;
If (typeof array = "string "){
For (; I <length; I ++ ){
Block. call (context, array. charAt (I), I, array );
}
} Else {
For (; I <length; I ++ ){
Block. call (context, array [I], I, array );
}
}
};
_ Function_forEach = function (fn, object, block, context ){
// Fn constant here is Function
For (var key in object ){
// Only traverse local properties
If (object. hasOwnProperty (key )){
// Equivalent to block (object [key], key)
Block. call (context, object [key], key, object );
}
}
};
Some examples of the original author (I crossed the wall !) :
Copy codeThe Code is as follows:
Function print (el, index ){
Alert (index + ":" + el)
}
ForEach ([1, 2, 3], print );
ForEach ({a: "aa", B: "bb", c: "cc"}, print );
ForEach ("situ zhengmei", print );
ForEach (document. styleSheets, function (el ){
If (el. href) alert (el. href)
});
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Copy codeThe Code is as follows:
Function Person (name, age ){
This. name = name | "";
This. age = age | 0;
};
Person. prototype = new Person;
Var fred = new Person ("Fred", 38 );
Fred. language = "English"; // very late binding
Fred. wife = "Wilma"; // very late binding
ForEach (fred, print)
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]