【JavaScript】常用陣列方法

Neptune Li
Li-NInja
Published in
3 min readSep 27, 2020

🚩 前言

這邊會列出幾個常用的陣列方法以及使用的方式。
以下使用 pokémonList 當做範例。

const pokémonList = [
{
name: '皮卡丘',
level: 99,
money: 100
},
{
name: '閃電鳥',
level: 20,
money: 110
},
{
name: '水箭龜',
level: 56,
money: 50
},
{
name: '卡蒂狗',
level: 66,
money: 1
},
{
name: '鯉魚王',
level: 33,
money: 999
},
];

for 迴圈

for 迴圈是最基本的使用方法,
不過在寫 TypeScript 時因為他無法使用箭頭函式,
所以會以使用 forEach 為主。

for (let i = 0; i < pokémonList.length; i++) {
console.log(pokémonList[i].name);
}

forEach

使用的方法與 for 迴圈 是一樣的。

pokémonList.forEach((pokémon) => {
console.log(pokémon.name);
});

map

他與 forEach 很像,
差別在於 map 可以 retrun
所以需要宣告一個變數來接收。
如果沒有 return 的話會回傳 undefined

const nameList = pokémonList.map((pokémon) => {
return {
pokémonName: pokémon.name
};
});

filter

return true 時會將結果回傳回去,
假如我要找出等級在 60 以上的 pokémon 時:

const hightLevel = pokémonList.filter((pokémon) => pokémon.level >= 60);

find

假設是要找一個特定的值時,
可以直接使用 find
他會將找到的第一筆資料做回傳,
當我要找皮卡丘有多少錢的時候:

const pikachuMoney = pokémonList.find((pokémon) => pokémon.name === '皮卡丘').money;

every

他的概念像是交集,
pokémonList 所有物件都符合才會回傳 true

const isHightLevel = pokémonList.every((pokémon) => pokémon.level >= 60);
// isHightLevel = false

some

他的概念像是聯集,
pokémonList 有部分的物件符合就會回傳 true

const isSomeHightLevel = pokémonList.some((pokémon) => pokémon.level >= 60);
// isSomeHightLevel = true

reduce

prev 是找出前一筆的值,
如果是第一筆就是套用給他的初始值 initValue
以下示範找出最大的金額。

const initValue = 0;const richer = pokémonList.reduce((prev, item) => {
return Math.max(prev, item.money);
}, initValue);

--

--