學習筆記-JS30-Day7-Array Cardio Day 2

vincentxu
4 min readMar 23, 2023

--

今日重點:

認識陣列的處理方法

程式碼:github
線上看:本日無

學習筆記:

方法

1. some()

2. every()

3. find()

4. findIndex()

5. splice()

some()應用

第1題

const Adult = people.some(person => new Date().getFullYear() - person.year >= 19)
console.log(Adult)

every()應用

第2題

const Adult = people.every(person => new Date().getFullYear() - person.year >= 19)
console.log(Adult)

find()應用

第3題

const comment = comments.find(coments => coments.id === 823423)
console.log(comment)

第5題

inventors.forEach(function(inventor){
inventor.years = inventor.passed-inventor.year
});
const yearsList = inventors.sort(function(a,b){
if ((a.passed - a.year) > (b.passed - b.year)){
return 1;
}else {
return -1;
}
})
console.table(yearsList);
//簡化 箭頭函式
inventors.forEach(inventor => inventor.years = inventor.passed-inventor.year);
const yearsList = inventors.sort((a,b) =>
(a.passed - a.year) > (b.passed - b.year) ? 1: -1 )
console.table(yearsList);

findIndex()應用 + splice()

第4題

const comment = comments.findIndex(coments => coments.id === 823423)
console.log(comment)

第5題

const comment = comments.findIndex(coments => coments.id === 823423)
const delComment = comments.splice(comment, 1)
console.log(comments)

第5題一樣是刪除不同用法,提供大家參考

//splice 直接在陣列中刪除,就不會恢復
const comment = comments.findIndex(coments => coments.id === 823423)
const delComment = comments.splice(comment, 1)
console.log(comments)

//slice 複製一個新陣列,拼接出刪除項目的前後,不影響原陣列
const newComment = [
...comments.slice(0, comment),
...comments.slice(comment+1)
]
console.log(newComment)

--

--

vincentxu
vincentxu

Written by vincentxu

熱愛學習、戶外運動,關心教育,曾任公部門主計,教育工作者/軟體工程師_嘗試將科技與使用者經驗設計導入教育_共同創辦一個線上教育平台,推廣自主學習與民主教育https://www.daoedu.tw/

No responses yet