JavaScript array.map()方法创建一个新数组,其输出是对此数组中的每个元素调用提供的函数。
array.map(callback[, thisObject]);
callback - 它从当前数组的元素生成新数组的元素。
thisObject - 要在执行回调时用作的对象。
返回创建的数组。
此方法是ECMA-262标准的JavaScript扩展;因此,它可能不存在于该标准的其他实现中。要使其工作,您需要在脚本顶部添加以下代码。
if (!Array.prototype.map) { Array.prototype.map=function(fun /*, thisp*/) { var len=this.length; if (typeof fun != "function") throw new TypeError(); var res=new Array(len); var thisp=arguments[1]; for (var i=0; i < len; i++) { if (i in this) res[i]=fun.call(thisp, this[i], i, this); } return res; }; }
<html> <head> <title>JavaScript Array map Method</title> </head> <body> <script type="text/javascript"> if (!Array.prototype.map) { Array.prototype.map=function(fun /*, thisp*/) { var len=this.length; if (typeof fun != "function") throw new TypeError(); var res=new Array(len); var thisp=arguments[1]; for (var i=0; i < len; i++) { if (i in this) res[i]=fun.call(thisp, this[i], i, this); } return res; }; } var numbers=[1, 4, 9]; var roots=numbers.map(Math.sqrt); document.write("roots is : " + roots ); </script> </body> </html>
运行上面代码输出
roots is : 1,2,3
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)