javascript 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
结果:
--------------------------------------------------------------------------------
[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
结果:
--------------------------------------------------------------------------------
2
5
9
|
下面看实例
代码如下 |
复制代码 |
<script language="JavaScript" type="text/javascript">
// 说明:Javascript Array 的 forEach 方法
// 整理:http://www.zzzyk.com
// 来源:http://www.hzhuti.com
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>
|
补充:网页制作,js教程