定义和用法
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意:
map()不会对空数组进行检测。map()不会改变原始数组。
语法
array.map(function(currentValue,index,arr), thisValue)
参数说明
| 参数 | 描述 | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| function(currentValue, index,arr) | 必须。函数,数组中的每个元素都会执行这个函数 函数参数:
|
||||||||
| thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 “this” 的值。 如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。 |
浏览器支持

实例 1
返回一个数组,数组中元素为原始数组的平方根:
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
var numbers = [4, 9, 16, 25];
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = numbers.map(Math.sqrt);
}
</script>
输出结果为:
2,3,4,5实例 2
数组中的每个元素乘于输入框指定的值,并返回新数组:
<p>点击按钮将数组中的每个元素乘于输入框指定的值,并返回新数组。</p>
<p>最小年龄: <input type="number" id="multiplyWith" value="10"></p>
<button onclick="myFunction()">点我</button>
<p>新数组: <span id="demo"></span></p>
<script>
var numbers = [65, 44, 12, 4];
function multiplyArrayElement(num) {
return num * document.getElementById("multiplyWith").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = numbers.map(multiplyArrayElement);
}
</script>