練習用資料
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 }
];
Q1
// Array.prototype.some()
// 可用在搜尋購物車標籤、檢查產品內包含的特定項目、陣列比較
// is at least one person 19 or older?
// 至少有一個人是19歲以上?
let ans = people.some(item => {
return new Date().getUTCFullYear() - item.year >= 19;
});
console.log(ans); //true
Q2
// Array.prototype.every()
// is everyone 19 or older?
//全部人都是19歲以上?
let ans2 = people.every(item => {
return new Date().getUTCFullYear() - item.year >= 19;
});
console.log(ans2); //false
Q3
// Array.prototype.find()
// 找出第一筆符合的物件本身,有多筆相同資料也只呈現第一筆
// Find is like filter, but instead returns just the one you are looking for
// find the comment with the ID of 823423
let ans3 = comments.find(item => {
return item.id === 823423;
})
console.log(ans3); //{text: "Super good1", id: 823423}
Q4
// Array.prototype.findIndex()
//找出陣列中第一筆符合的元素並回傳其位置序列,找不到會回傳-1
// Find the comment with this ID
let ans4 = comments.findIndex(item => {
return item.id === 823423;
})
console.log(ans4); //1 ,陣列從0開始
Q5-使用splice
// delete the comment with the ID of 823423
//splice(刪除的位置,刪除的數量,新加入的內容)
//splice(0,0,xxx) = 單純加入xxx內容
const ans5 = comments.splice(ans4, 1);
console.log(ans5, comments);
//不動原始資料的做法
const ans8 = [...comments].splice(ans4, 1);
console.log(ans8, comments);
Q5-使用slice
// delete the comment with the ID of 823423
const ans6 = comments.slice(0, ans4);
const ans7 = comments.slice(ans4 + 1);
console.log([...ans6, ...ans7], comments);