学无先后,达者为师

网站首页 编程语言 正文

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

作者:小五Ivy 更新时间: 2022-02-20 编程语言

如实现:[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对象

原文链接:https://blog.csdn.net/weixin_44471622/article/details/105659858

栏目分类
最近更新