1.概念
map()方法定义在JavaScript的Array中,它返回一个新的数组。
数组中的元素为原始数组调用函数处理后的值。
注意:
1.map()不会对空数组进行检测
2.map()不会改变原始数组
2.语法
array.map(function(currentValue, index, arr), thisIndex)
3.实例
3.1 把数组l里的每一项转为Number 或 String 或 Boolean
let list = ["11",22,"33",44,"55"]
let newListNumber = list.map(Number)
let newListString = list.map(String)
let newListBoolean = list.map(Boolean)
console.log("list=>",list) // ['11', 22, '33', 44, '55']
console.log("newListNumber=>",newListNumber) //[11, 22, 33, 44, 55]
console.log("newListString=>",newListString) //['11', '22', '33', '44', '55']
console.log("newListBoolean=>",newListBoolean) // [true, true, true, true, true]
3.2 把数组l里的每一项乘2
let list = ["11",22,"33",44,"55"]
let newList = list.map(item=>item*2)
console.log("list=>",list) //['11', 22, '33', 44, '55']
console.log("list=>",newList) //[22, 44, 66, 88, 110]
3.3 自定义属性名
let list = [
{ id: 0, title: "星期日", state: 0 },
{ id: 1, title: "星期一", state: 1 },
{ id: 2, title: "星期二", state: 1 }
]
let newList = list.map(item => {
if (item.state === 0) {
item.state = '休息'
} else if (item.state === 1) {
item.state = '工作'
}
return { value: item.id, desc: item.title, workState: item.state }
})
console.log(newList)
// 0: { value: 0, desc: '星期日', workState: '休息' }
// 1: { value: 1, desc: '星期一', workState: '工作' }
// 2: { value: 2, desc: '星期二', workState: '工作' }