javascript/javascript30

[javascript30]Array Cardio Day 2

소영 2021. 7. 15. 14:03
Array Cardio Day 2

찾기 메서드로 배열의 프로퍼티에 접근한다.

 

1. .some()과 .every()의 차이점과, .find()와 .findIndex()의 차이점 확인

2..slice()활용과 this의 바인딩

 

코드
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Array Cardio 💪💪</title>
</head>
<body>
  <p><em>Psst: have a look at the JavaScript Console</em> 💁</p>
  <script>
    // ## 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() // 적어도 한 사람은 19세 이상인가요?
    const isAdult = people.some(person=>(new Date().getFullYear())-person.year>=19);
    console.log(isAdult);//true
    // Array.prototype.every() //모두 19세 이상인가요?
    const allAdult = people.every(person=>(new Date().getFullYear())-person.year>=19);
    console.log(allAdult);//false
    // Array.prototype.find()
    // 찾기는 필터와 같으나 찾으려는 항목만 반환합니다.
    // 823423이라는 아이디로 의견을 찾다.
    const comment = comments.find(comment=>comment.id==823423);
    console.log(comment);//{text: "Super good", id: 823423}
    // Array.prototype.findIndex()
    // 이 ID로 주석 찾기
    // 아이디 823423으로 주석을 삭제하다.
    const index = comments.findIndex(comment=>comment.id==823423);
    console.log(index);//1
    //comments.splice(index, 1);
    
    const newComments = [
        ...comments.slice(0,index),//index가 1이니까 0,1만 나옴
      ...comments.slice(index+1)//2이기때문에 0,1에 추가로 2,3나옴

        ]
    console.table(newComments);
  </script>
</body>
</html>

 

알게된 문법
.some()

arr.some(callback[, thisArg])

배열에서 값이 맞는지 검토하기 위해 사용하는 메서드

thisArg->조건작성

조건이 하나라도 참이면 true 거짓이면 false를 반환한다.

 

.every()

.some()메서드와 같이 배열에서 값이 맞는지 검토하기 위해 사용한다.

.some()메서드와 다른 점은 조건이 모두 참이이어야 true 거짓이면 false를 반환한다.

 

.find()

arr.find(callback[, thisArg])

찾는 것은 .filter()메서드와 같지만 찾으려는 항목만 반환한다.

 

.findIndex

arr.findIndex(callback(element[, index[, array]])[, thisArg])

.find()와 조건작성방법은 같으나 찾으려는 인덱스를 반환한다는 차이점이 있다.