DAY 10
1
Modern Web

## Day10: 針對陣列的操作練習(三)

https://wcc723.github.io/javascript/2017/06/29/es6-native-array/

https://github.com/sawyerbutton/Difference-between-Splice-Slice-Split

``````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 },
];
``````

1.some() : 只要陣列中有其中一項符合條件就return true
is at least one person 19 or older?

``````const isAdult = people.some(function (person) {
const currentYear = new Date().getFullYear();
return currentYear - person.year >= 19;
});
``````

ES6寫法:

``````const isAdult = people.some (
person => ((new Date()).getFullYear()) - person.year >= 19);
``````

2.every() : 陣列中全部都符合條件才return true
is everyone 19 or older?

``````const allAdults = people.every(function (person) {
const currentYear = new Date().getFullYear();
return currentYear - person.year >= 19;
});
``````

ES6寫法:

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

3.find()
find the comment with the ID of 823423

``````const comment = comments.find(function (comment) {
return comment.id === 823423;
});
``````

ES6寫法:

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

4.findIndex()
delete the comment with the ID of 823423

``````const index = comments.findIndex(function (comment) {
return comment.id === 823423;
});
``````

ES6寫法:

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

splice() : 會影響原始的陣列，不需要再重新命名

``````comments.splice(index, 1)
``````

slice() : 不會修改原本的陣列，而是回傳由原本的陣列淺層複製的元素。

``````const newComments = [
...comments.slice(0, index),
...comments.slice(index + 1),
];
``````

codePen

javascript30