一、定义和注意点
map()方法定义在JavaScript的Array中,它返回一个新的数组,数组中的元素为原始数组调用函数处理后的值。
注意:
1.map()不会对空数组进行检测
2.map()不会改变原始数组
二、语法
1.array.map(function(currentValue, index, arr), thisIndex)
function(currentValue, index, arr):必须。为一个函数,数组中的每个元素都会执行这个函数。其中函数参数:
1.currentValue:必须。当前元素的的值。
2.index:可选。当前元素的索引。
3.arr:可选。当前元素属于的数组对象。
thisIndex:可选。对象作为该执行回调时使用,传递给函数,用作"this"的值。
三、应用场景
1.两个数组合并成一个数组对象
// 合并数组对象
let array1 = ['周一','周二','周三','周四','周五','周六','周日']
let array2 = ['上班','上班','出差','出差','团建','休息','约会']
// 将两个数组合并成一个数组并返回
let data = array1.map((item,index) => {
return {
name:item,
value:array2[index]
}
})
console.log('这是合并的数组对象data',data)
2.返回由原数组中每个元素的平方组成的新数组
let array = [1, 2, 3, 4, 5];
let newArray = array.map((item) => {
return item * item;
})
console.log(newArray) // [1, 4, 9, 16, 25]
3.返回一个数组,数组中元素为原始数组的平方根:
var numbers = [4, 9, 16, 25];
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = numbers.map(Math.sqrt);
//x.innerHTML = Math.sqrt(4)
}
输出结果为:2,3,4,5
4.数组中的每个元素乘于输入框指定的值,并返回新数组:
var numbers = [65, 44, 12, 4];
function multiplyArrayElement(num) {
return num * document.getElementById("multiplyWith").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = numbers.map(multiplyArrayElement);
}
输入框-输入10
结果:650,440,120,40