Would you like to clone this notebook?

When you clone a notebook you are able to make changes without affecting the original notebook.

Cancel

JavaScript array methods (commonly)

node v14.20.1
version: 1.0.0
endpointsharetweet
let fruits = ['Apple', 'Banana'] fruits.length
array.length 可以用來取得陣列中元素的個數
let last = fruits[fruits.length - 1]
常使用 array[ array.length - 1] 來取得最後一個元素
fruits.push('Orange') fruits
可以使用 push() 從後面加入一個 元素 *可以同時加入多個,例如 push('A', 'B')
const orange = fruits.pop()
使用 array.pop() 可以後面拿一個 元素 出來
fruits.shift()
透過 array.shift() 可以從前面拿一個 元素 出來
fruits.unshift("Apple") fruits
透過 array.unshift() 可以從前面插入一個 元素
fruits = ['Apple', 'Banana', 'Orange']; fruits.indexOf('Banana')
可以用 indexOf() 來取得 某元素在 陣列 中的位置,如果不在陣列中會回傳 -1
fruits.splice(0, 1); fruits
splice(位置, 刪除個數, 加入的元素) 可以用來從中間刪除、插入元素 通常 刪除個數 / 加入的元素 不會一起用 通常 位置 會使用 indexOf 組合再一起用 例如,把 Banana 刪除 fruits.splice(fruits.indexOf("Banana"), 1);
fruits = ['Apple', 'Banana', 'Orange']; fruits.splice(fruits.indexOf("Banana"), 1); fruits
在 Banana 之前加入一個 Watermelon
fruits = ['Apple', 'Banana', 'Orange']; fruits.splice(fruits.indexOf("Banana"), 0, 'Watermelon'); fruits
或者在 在 Banana 之後加入一個 Watermelon
fruits = ['Apple', 'Banana', 'Orange']; fruits.splice(fruits.indexOf("Banana") + 1, 0, 'Watermelon'); fruits
let fruitsA = ['Apple', 'Banana']; let fruitsB = ['Watermelon', 'Orange']; fruitsA.concat(fruitsB)
concat 可以用來將兩個陣列合併
const axios = require('axios'); const response = await axios.get("https://shopee.tw/api/v4/search/search_items?by=pop&limit=30&match_id=79684414&newest=0&order=desc&page_type=shop&scenario=PAGE_OTHERS&version=2"); let items = response.data.items;
items = items.map(function(item, index, array) { return { name: item.item_basic.name, image: "https://cf.shopee.tw/file/" + item.item_basic.image }; });
map 會依序的將陣列裡的每一個 元素 傳進函數做處理,再傳回一個處理過的陣列 常用來將複雜的陣列資料,只留下需要的欄位。
items.filter(function(item, index, array) { return item.name.includes("女"); });
filter 會依序的將陣列裡的每一個 元素 傳進函數做篩選,再傳回一個處理過的陣列
response.data.items.reduce(function(accumulator, item, index, array) { return accumulator + item.item_basic.sold; }, 0);
array.reduce() 會依序的將每一個元素進行運算傳進函數做運算,在回傳運算後的結果 常見的功能是將陣列中某一個數值做加總 *最後面的 0 代表著初始值,而 accumulator 是上一回運算的結果
網路上流傳著一張圖片,可以用來解釋這三個函式的功能 https://res.cloudinary.com/practicaldev/image/fetch/s--fR01rwJz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/3158n4nhe7gt24wvl2u4.png
items = response.data.items .map(item => ({ name: item.item_basic.name, image: "https://cf.shopee.tw/file/" + item.item_basic.image })) .filter(item => item.name.includes("女"));
.map 和 .filter 常常混在一起用,並且使用 arrow function 的方式撰寫
response.data.items.find(function(item, index, array) { return item.item_basic.name.includes("女"); });
find 和 filter 很像,但他只回傳一筆結果
response.data.items.findIndex(function(item, index, array) { return item.item_basic.name.includes("撞色"); });
findIndex 算是 find 及 indexOf 的結合體,會回傳第一筆符合資料的位置
Loading…

no comments

    sign in to comment