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((newPerso// [ { 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))

原文鏈接:https://blog.csdn.net/ruffaim/article/details/82260280


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM