给定一个数组,让数组的每一项都乘以2几种实现方法

如实现:[1,2,3] => [2,4,6]

方法:forEach / map / for / for…in / for… of / reduce

1.forEach

如果要使用数组的forEach()方法对其改值时,需要直接通过arr[i]这种方式来更改。

let arr=[1,2,3]

arr.forEach((item, index) => {     
    item=item*2 //不生效==>arr=[1,2,3]
    arr[index]=item*2 //==>arr=[2,4,6]
})
2.map
let cie = arr.map(item=>item*2)
//cie=>[2,4,6]
3. for
for (let i = 0; i < arr.length; i++){
      arr[i]=arr[i]*2
}
4. for…in
for (let key in arr) {
      arr[key]=arr[key]*2
}
for…of

一个Map对象在迭代时会根据对象中元素的插入顺序来进行 — 一个 for…of 循环在每次迭代后会返回一个形式为[key,value]的数组。
构造函数: Map() —> 创建Map对象

//Map可以使用for..of循环来实现迭代:
for (let [index, elem] of new Map(arr.map((item, i) => [i, item]))) {
      arr[index] = elem * 2
}

new Map(arr.map((item, i) => [i, item]))==>//{0 => 2, 1 => 4, 2 => 6}
reduce
let cie = arr.reduce((total, value, index, arr) => {
      total.push(value * 2)
      return total
    },[])
//cie=>[2,4,6]
Array.from
let cie=Array.from([1,2,3],x=>x*2)
//cie=>[2,4,6]
  • Array.from() 方法从一个类数组或可迭代对象创建一个新的, 浅拷贝的数组实例
  • Array.fom(arrayLike[,mapFn[,thisArg]])
    • arrayLike 想要转换成数组的伪数组对象或者可迭代对象
    • mapFn 可选 ----- 如果指定了该参数, 新数组中的每个元素会执行该回调函数
    • thisArg 可选 ----- 执行回调函数mapFn时的this对象
  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值