JavaScript 的 数组 对象内置了 map 方法,可以用来遍历数组,为数组的每一个元素调用一个回调函数进行处理,处理完成后,返回 一个新的数组。
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
array.map(function(currentValue,index,arr), thisValue)
参数 | 描述 |
---|---|
function(currentValue, index, arr) | 必须。数组每个元素需要执行的函数。 |
thisValue | 可选。对象作为该执行回调时使用,传递给函数,用作 “this” 的值。 如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。 |
参数 | 描述 |
---|---|
currentValue | 必需。当前元素 |
index | 可选。当前元素的索引 |
arr | 可选。当前元素所属的数组对象 |
返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
该函数只支持 JavaScript 1.6 即以上版本。
使用 map 循环遍历数组的每一个元素
<!DOCTYPE html>
<html>
<head>
<title>JavaScript map循环遍历数组的每一个元素</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
var arr = new Array(1, 4, 9, 16, 25, 36);
console.log("Arr =", arr);
var newArr = arr.map(Math.sqrt);
console.log("NewArr =", newArr);
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们首先,定义了一个数组 arr,接着,我们为该数组调用 map 函数,同时,传入 map 函数的回调函数为 Math.sqrt,即,对数组的每一个元素求平方根。
最后,我们使用 newArr 接受 map 函数的返回值,我们发现,map 函数返回的新的数组是原数组的平方根。
使用 map 循环遍历数组的每一个元素
<!DOCTYPE html>
<html>
<head>
<title>JavaScript map循环遍历数组的每一个元素</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
var arr = new Array(1, 4, 9, 16, 25, 36);
console.log("Arr =", arr);
function walk(currentValue, index, arr){
return currentValue + index;
}
var newArr = arr.map(walk);
console.log("NewArr =", newArr);
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们定义了一个 walk 函数,该函数接受三个参数,一个为当前值,一个为当前的索引,最后一个为数组,同时,在该函数里,我们返回了当前值与当前索引的和。
最后,我们将 walk 函数传入数组 arr 的 map 函数里,同时使用 newArr 接受 map 函数的返回值,我们发现,map 函数返回的新的数组将原数组的每一个元素的值加上了当前的索引。
JavaScript 的数组对象内置了 map 方法,可以用来遍历数组,为数组的每一个元素调用一个回调函数进行处理,处理完成后,返回一个新的数组。JavaScript 数组 map 语法:
array.map(function(currentValue,index,arr), thisValue)