1、定义
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
2、语法
array.map(function(currentValue,index,arr), thisValue)
3、参数说明
返回值
4、用法
map() 方法按照原始数组元素顺序依次处理元素。
5、注意事项
map() 不会对空数组进行检测。
map() 不会改变原始数组。
6、初级应用实例讲解
//1、对数组array的每个元素乘2------------------------------
const array = [1, 4, 9, 16];
const mapArray = array.map(x => x * 2);
console.log(mapArray);
//打印 [2, 8, 18, 32]
//2、返回由原数组中每个元素的平方组成的新数组--------------------
const array = [1, 2, 3, 4, 5];
const mapArray = array.map((item) => {
return item * item;
})
console.log(mapArray);
//打印[1, 4, 9, 16, 25]
7、两个数组合并成一个数组对象。
const array1 = ['周一','周二','周三','周四','周五','周六','周日']
const array2 = ['1','2','3','4','5','6','7']
const newArr = array1.map((item,index) => {
return {
name:item,
id:array2[index]
}
})
console.log(newArr)
//打印-------------------------
[
{
"name": "周一",
"id": "1"
},
{
"name": "周二",
"id": "2"
},
{
"name": "周三",
"id": "3"
},
{
"name": "周四",
"id": "4"
},
{
"name": "周五",
"id": "5"
},
{
"name": "周六",
"id": "6"
},
{
"name": "周日",
"id": "7"
}
]
8、返回拼接数组users里的两个键值。
const users = [
{firstName : "White", lastName: "Green"},
{firstName : "Red", lastName: "Pink"},
{firstName : "Yellow", lastName: "Black"}
];
const userFullnames = users.map(function(element){
return `${element.firstName} ${element.lastName}`;
})
console.log(userFullnames);
//打印 ["White Green","Red Pink","Yellow Black"]
9、map中的this值。
const arr = [2, 3, 5, 7]
const newArr = arr.map(function(element, index, array){
return element * this;
}, 80);
console.log(newArr)
//打印 [160,240,400,560]
//分析:
//function()在每个数组元素上调用该回调,并且该map()方法始终将current element,index当前元
//素的of和整个array对象传递给它。
//该this参数将在回调函数中使用。默认情况下,其值为undefined。这里this值更改为数字的方法80,如果
//不写this指向的是全局,这种用法还是不常见的,做个了解就行。