今日任務:認識陣列的方法2
資料
const people = [
{ name: 'Wes', year: 1988 },
{ name: 'Kait', year: 1986 },
{ name: 'Irv', year: 1970 },
{ name: 'Lux', year: 2015 },
]
const comments = [
{ text: 'Love this!', id: 523423 },
{ text: 'Super good', id: 823423 },
{ text: 'You are the best', id: 2039842 },
{ text: 'Ramen is my fav food ever', id: 123523 },
{ text: 'Nice Nice Nice!', id: 542328 },
]
範例: 是否至少有一位超過19歲的人?
const IsAudult = people.some((person) => {
const currentYear = new Date().getFullYear(); //取得年份
return currentYear - person.year >= 19;
});
console.log('至少一人超過19歲?', IsAudult);
範例: 是否全部人都超過19歲的人?
const AllAudult = people.every((person) => {
const currentYear = new Date().getFullYear();
return currentYear - person.year >= 19;
});
console.log('全部人超過19歲?', AllAudult);
範例: 找出id=823423的第一個人
const comment = comments.find((comment) => {
return comment.id === 823423;
});
console.log('id=823423的第一個人', comment);
範例: 找出id=823423的人的index
const index = comments.findIndex((comment) => {
return comment.id === 823423;
});
console.log('id=823423的第一個人的id= ', index);
comments.splice(index, 1)
console.log(comments) //原陣列改變
const newComments = [...comments.slice(0, index), ...comments.slice(index + 1)];
console.log(newComments);
console.log('console.log(comments)', comments);
而且沒有影響到原本的陣列
方法3(影片中沒有)
const newComments = comments.filter(commet=>(commet.id !== 823423))
console.log(newComments)
今日學習到的:
效果連結:連結
參考連結:
MDN:some
MDN:findIndex
MDN:splice
MDN:slice