Javascript 1.6 数组新增方法介绍之 forEach() – 示例

打印数组内容:

代码:
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
结果:

用对象的方法打印数组内容:

代码:
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
结果: