본문 바로가기
DEV/JS30

[JS30] day 7 - Array cardio day 2

by newjp 2021. 12. 12.

1. Array.some()

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

// Arrow function
const currentYear = (new Date()).getFullYear();
const isAdult = people.some(person => (currentYear - person.year >= 19));

Array에 있는 객체 중 찾고자 하는 조건에 맞는 객체가 하나라도 있으면 참을 반환

모든 요소가 통과하지 못하면 거짓을 반환 (빈 배열은 항상 거짓)

2. Array.every()

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

// Arrow function
const currentYear = (new Date()).getFullYear();
const isAdult = people.every(person => (currentYear - person.year >= 19));

Array에 있는 객체 중 전부 조건에 맞으면 true, 하나라도 맞지 않으면 false 반환 (빈 배열은 항상 참)

3. Array.find()

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

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

Array에 있는 모든 요소에 대해 콜백 함수를 실행하여 콜백 함수의 반환 값이 참이면 해당 요소를 반환, 찾는 값이 배열에 없으면 undefined 반환

4. Array.findIndex()

const index = comments.findIndex(comment => comment.id == 823423);
    console.log(index+1+'번째에 있습니다');

Array에 있는 모든 요소 중 찾는 값이 어느 인덱스에 있는 지 인덱스를 반환

5. Array.splice(startIndex,endIndex);

comments.splice(index, 2);
console.table(comments)

python의 slice와 같음, 자르기 시작할 index와 끝낼 인덱스를 넣어주면 그 부분만 없애 줌

Array 자체에 영향을 미침!!

6. 원본Array 손상 없이 Array가공 하여 새로운 Array에 할당 하기

const newComment = [
      ...comments.slice(0, index),
      ...comments.slice(index+1)
]

슬라이스 된 요소들로 새로운 Array를 생성할 수 있음

0부터 index까지 slice, index+1부터 끝까지 slice하는데 두 번의 slicing을 했으므로 기본적으로는 두 개의 객체가 생겨 newComment의 Array에 저장됨, 이때는 각 slice앞에 하나하나의 객체를 의미하는 ...을 써 주어야 우리가 기대하는 Array가 반환이 된다

  • ... (비 구조화 할당 구문 중 전개 연산자) 비구조화 할당(destructuring assignment) 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 자바스크립트 표현식(expression)이다. 간단하게 정리하면 배열 [], 혹은 객체 {} 안의 값을 편하게 꺼내 쓸 수 있는 문법1. Array.some()Array에 있는 객체 중 찾고자 하는 조건에 맞는 객체가 하나라도 있으면 참을 반환2. Array.every()Array에 있는 객체 중 전부 조건에 맞으면 true, 하나라도 맞지 않으면 false 반환 (빈 배열은 항상 참

 

'DEV > JS30' 카테고리의 다른 글

[JS30] day 9 - 14 Must know dev tools tricks  (0) 2021.12.28
[JS30] day 8 - Fun with HTML5 Canvas  (0) 2021.12.12
[JS30] day 6 - Ajax type ahead  (0) 2021.12.12
[JS30] day 5 - Flex panels image gallery  (0) 2021.12.09
[JS30] day 4 - Array cadio day 1  (0) 2021.12.09