陣列相關方法2

Ref: JavaScript30

some()  確認有沒有人符合條件

給予條件→找出是否有一個人(或以上)符合條件。

//共用陣列資料
const people = [
 { name: 'Wes', year: 1988 },
 { name: 'Kait', year: 1986 },
 { name: 'Irv', year: 1970 },
 { name: 'Lux', year: 2015 }
];

確認是否有人已滿19歳

/*****【方法一】function*************/
const isAdult1=people.some(

function(person){
 //getFullYear?
 const currentYear=new Date().getFullYear();
 if(currentYear-person.year>=19){
 return true;
 }
}
 
);


/*****【方法二】arrow function*******/
const isAdult2=people.some(person => new Date().getFullYear()-person.year>=19);
console.log(isAdult2);//true

every()  確認是否全員符合條件

給予條件→找出是否所有人都符合條件。

確認是否全員都滿19歳

const everyAdult=people.every(person => new Date().getFullYear()-person.year>=19);

console.log(everyAdult);//false

find()  找出特定的項目

//共用陣列資料
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 }
];

找出id為【823423】的留言

const comment=comments.find(comment => comment.id===823423);

console.log(comment);
/**
Object {
  id: 823423,
  text: "Super good"
}
**/

findIndex 找出特定項目的陣列編號

【※注意】陣列編號由 0 開始算。編號 0 為第1項、編號 1 為第 2 項。

找出id為【823423】的陣列編號

const index=comments.findIndex(comment => comment.id===823423);

console.log(index);//1 ←comments[1];

splice 刪除特定編號的陣列

參考文章
【※注意】只能指定編號刪除。

comments.splice(1, 1);

//然後comments就會少一項了。但不保留沒刪除前的内容。

slice 摘取陣列

參考文章

也可以達到刪除特定項目陣列的效果。
但方法是擷取保留項目,像是指定列印頁數。

共5頁的資料→只列印【第1頁】、【第3-5頁】→最後印出來的資料就會少了第2頁

用slice可以同時保留刪除前的陣列與刪除後的陣列。

const newComments=[
 ...comments.slice(0, 1),//only return comments[0]
 ...comments.slice(2)//omit end value
 //保留slice[0], slice[2-4]→等於去掉slice[1]
]; 

console.log(newComments);
/**
const newC=[
 ...comments.slice(0, 1),//only return comments[0]
 ...comments.slice(2)//omit end value
];
**/