日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

給定一個數組,讓數組的每一項都乘以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

欄目分類
最近更新