Javascript中的Map()函数

概述

Array.map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值,同时不会改变原来的数组。

用法
Array.map(callback);
示例
//简单数组
const arr = [1, 3, 4, 5, 6, 7, 8, 10];

const cube = (num) => {
    return num * num;
}

const res = arr.map(cube);//[ 1, 9, 16, 25, 36, 49, 64, 100 ]

// or

const res = arr.map((num)=>{
    return num * num;
})
//[ 1, 9, 16, 25, 36, 49, 64, 100 ]

//对象数组和构造器
const OjbArray = [{
    name: 'a',
    age: 18,
    isLikeEat: true,
    isLikeSleep: true
}, {
    name: 'b',
    age: 19,
    isLikeEat: true,
    isLikeSleep: true
}, {
    name: 'c',
    age: 22,
    isLikeEat: true,
    isLikeSleep: true
}];

const Person = (target) => {
    return {
        name: target.name || 'default',
        age: target.age || 18,
        _eat: function() {
            console.log(target.isLikeEat ? 'i like eat' : 'i dont like eat');
        },
        _sleep: function() {
            console.log(target.isLikeSleep ? 'i like sleep' : 'i dont like sleep')
        }
    }
}

let newPersons = OjbArray.map(Person);
console.log((newPersons));

// [ { name: 'a',
//     age: 18,
//     _eat: [Function: _eat],
//     _sleep: [Function: _sleep] },
//   { name: 'b',
//     age: 19,
//     _eat: [Function: _eat],
//     _sleep: [Function: _sleep] },
//   { name: 'c',
//     age: 22,
//     _eat: [Function: _eat],
//     _sleep: [Function: _sleep] } ]

注意 ⚠️
  • 当和parseInt()函数配合使用 将字符转成数字的时候,可直接
['1', '2'].map(str => parseInt(str));
//or
['1', '2'].map(Number)
  • 本质上是用元素作为函数参数去调用函数,所以无需加上参数
//这种写法是错误的
const arr = [1, 3, 4, 5, 6, 7, 8, 10];

const cube = (num) => {
    return num * num;
}

const res = arr.map(cube(num))

你可能感兴趣的:(JavaScript)