js map函数的使用

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: '工作' }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值