CopyCode The 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]