前端入門學習筆記(三十七)JavaScript入門(十六)數組常用的四種方法 forEach、map、find、indexOf

forEach

數組的forEach有三個可選參數,value, index, arr,直接上例子比較容易懂一些,對應值、下標、數組。
並且forEach 沒有返回值。我覺得是用來替代for的很好用的方法(因爲這樣我們就不需要用.length獲取數組長度了)

let arr = [1, 2, 3]
let ans = arr.forEach((value, index, arr) => {
  console.log(`value = ${value}  index = ${index}  index = ${arr}`)
//value = 1  index = 0  arr = 1,2,3
//value = 2  index = 1  arr = 1,2,3
//value = 3  index = 2  arr = 1,2,3
})
console.log(ans)
//undefine

當然可以只前兩個參數,如(value,index)這樣的形式。

map

map有返回值,且map參數與forEach相同,有三個可選參數,value, index, arr,爲對應值、下標、數組。
直接上例子比較容易懂一些,

let arr = [1, 2, 3]
let map = arr.map((value, index, arr) => {
  console.log(`value = ${value}  index = ${index}  arr = ${arr}`)
  return 2 * value
//value = 1  index = 0  arr = 1,2,3
//value = 2  index = 1  arr = 1,2,3
//value = 3  index = 2  arr = 1,2,3
})
console.log(map)
//[ 2, 4, 6 ]

通過輸出可以看到結果,數組從[1, 2, 3]變爲[ 2, 4, 6 ],因爲我們在return 爲 2*value。將所有值乘2後返回,生成新的數組

find

find會返回符合條件的第一個value

let arr = [1, 2, 3]
let find = arr.find(value => {
  return value > 1
})
console.log(find)

indexOf

indexOf()方法返回在數組中可以找到一個給定元素的第一個索引,如果不存在,則返回-1。
這個的用法比較多,如方法確定多個值在數組中的位置等,可查看官方手冊
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

此處僅演示一個比較常用的方法

let arr = [1, 2, 3]
let indexOf = arr.indexOf(2)
console.log(indexOf)
//1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章