To print the contents of an array:
Code:
--------------------------------------------------------------------------------
The code is as follows |
Copy Code |
function Printelt (element, index, array) { Document.writeln ("[" + Index + "] is" + element + "<br/>"); } [2, 5, 9].foreach (Printelt); Prints: [0] is 2 [1] is 5 [2] is 9 Results: -------------------------------------------------------------------------------- [0] is 2 [1] is 5 [2] is 9 |
The
Prints the contents of the array using the object's method:
Code:
------------------------------------------------------------------------------- -
The code is as follows |
Copy Code |
var writer = { SB: [], Write:function (s) { This.sb.push (s); }, Writeln:function (s) { This.write (S + "<br/>"); }, Tostring:function () { Return This.sb.join (""); } }; [2, 5, 9].foreach (Writer.writeln, writer); Document.writeln (Writer.tostring ()); Prints: 2 5 9 Results: -------------------------------------------------------------------------------- 2 5 9 |
Look at the example below
The code is as follows |
Copy Code |
<script language= "JavaScript" type= "Text/javascript" >
Description: The ForEach method for Javascript Array Finishing: Http://www.111cn.net Source: Http://www.111cn.net
if (! Array.prototype.forEach) { Array.prototype.forEach = function (Fun/*, thisp*/) { var len = this.length; if (typeof fun!= "function") throw new TypeError ();
var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) Fun.call (Thisp, this[i], I, this); } }; }
</script> |