JavaScript Array map() 方法


返回一个数组,数组中元素为原始数组的平方根:

  1. var numbers = [4, 9, 16, 25];
  2.  
  3. function myFunction() {
  4. x = document.getElementById("demo")
  5. x.innerHTML = numbers.map(Math.sqrt);
  6. }
运行一下

输出结果为:

2,3,4,5

定义和用法

map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

map() 方法按照原始数组元素顺序依次处理元素。

注意: map() 不会对空数组进行检测。

注意: map() 不会改变原始数组。


浏览器支持

表格中的数字表示支持该方法的第一个浏览器的版本号。
方法







map() Yes 9 1.5 Yes Yes


语法

  1. array.map(function(currentValue,index,arr), thisValue)

参数说明

参数 描述
function(currentValue, index,arr) 必须。函数,数组中的每个元素都会执行这个函数
函数参数:
参数 描述
currentValue 必须。当前元素的值
index 可选。当期元素的索引值
arr 可选。当期元素属于的数组对象
thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值为 "undefined"

技术细节

返回值: 返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
JavaScript 版本: 1.6

更多实例

实例

数组中的每个元素乘于输入框指定的值,并返回新数组:

  1. var numbers = [65, 44, 12, 4];
  2.  
  3. function multiplyArrayElement(num) {
  4. return num * document.getElementById("multiplyWith").value;
  5. }
  6.  
  7. function myFunction() {
  8. document.getElementById("demo").innerHTML = numbers.map(multiplyArrayElement);
  9. }
运行一下