1. Array APIs
배열 API에 관한 연습 문제들이다.
// ## Array Cardio Day 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 }
];
// Some and Every Checks
// Array.prototype.some() // is at least one person 19 or older?
// Array.prototype.every() // is everyone 19 or older?
const someAge = people.some(function(person) {
const currentYear = (new Date()).getFullYear();
if (currentYear - person.year >= 19){
return true;
}
});
console.log(someAge);
const everyAge = people.every(person => (new Date()).getFullYear() - person.year >= 19);
console.log(everyAge);
// 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
const findId = comments.find(comment => comment.id === 823423);
console.log(findId);
// Array.prototype.findIndex()
// Find the comment with this ID
// delete the comment with the ID of 823423
const index = comments.findIndex(comment => comment.id === 823423);
console.log(index);
const removed = comments.splice(index, 1);
console.table(removed);
console.table(comments);
const input = comments.splice(index, 0, findId);
console.table(comments);
const newComments = [
...comments.slice(0, index),
...comments.slice(index + 1)
];
console.table(newComments);
1) some, every
- some API는 배열의 요소 중 하나라도 주어진 조건을 만족한다면 true를 반환하고 그렇지 않으면 false를 반환한다.
- every API는 배열의 모든 요소가 주어진 조건을 만족할 때 true를 반환하고, 하나라도 만족하지 않으면 false를 반환한다.
2) find, findIndex
- find API는 filter API와 유사하게, 주어진 조건을 만족하는 배열의 요소를 찾으나, 조건을 만족하는 첫 번째 요소만을 반환한다. 만족하는 요소가 없는 경우 undefined를 반환한다.
- findIndex API는 주어진 조건을 만족하는 배열의 첫 번째 요소의 인덱스를 반환한다.
3) slice, splice
- slice API는 slice(start, end) 형식으로 사용한다. start부터 end-1까지의 복사본을 새로운 배열을 반환하며, 원본 배열은 변하지 않는다. start를 입력하지 않으면 배열의 인덱스 0부터, end를 입력하지 않으면 배열의 length까지 복사하여 반환한다.
- splice API는 splice(start, deleteCount, item1, item2, ...) 형식으로 사용한다. start 지점부터 deleteCount에 해당하는 숫자만큼 요소를 삭제하며, item1, item2, ...를 추가한다. 반환값은 제거한 배열이며, 원본 배열은 요소의 제거나 추가가 이루어진 값으로 변형된다.
[Javascript] 09. Dev Tools Domination (0) | 2021.04.20 |
---|---|
[Javascript] 08. Fun with HTML5 Canvas (0) | 2021.04.20 |
[Javascript] 06. Ajax Type Ahead (0) | 2021.04.17 |
[Javascript] 05. Flex Panel Gallery (0) | 2021.04.16 |
[Javascript] 04. Array Cardio Day 1 (0) | 2021.04.15 |
댓글 영역