20241107 자바스크립트 Object.toString(), Array.find()

클래스 인스턴스 값들을 하나의 문자열로 만들고 싶을 때

class 내부에 toString() 메서드를 만들고 다른 파일에서 \`${변수명}\`;하면 자바스크립트에서 자동으로 toString() 메서드를 불러와준다.

Dog 클래스가 다음과 같을 때,

class Dog {
  name;
  color;

  constructor(name, color) {
    this.name = name;
    this.color = color;
  }

  toString() {
    return `${this.name} 강아지는 ${this.color}이다.`;
  }
}
const myDog = new Dog("바둑이", "검정흰색");

console.log(`${myDog}`);

//// 출력
// 바둑이 강아지는 검정흰색이다.

위와 같이 인스턴스 값들을 toString() 메서드를 사용해 하나의 문자열로 나타낼 수 있다.


Array.find()

find() 메서드는 다음과 같이 동작한다.
배열 내 특정 조건을 만족하는 요소가 있을 때 : 첫 번째 요소 반환
배열 내 특정 조건을 만족하는 요소가 하나도 없을 때 : undefined 반환

const array1 = [5, 12, 8, 130, 44];

const found = array1.find((element, index) => {
  console.log(index);
  return element > 10;
});

console.log(found);

//// 출력
// 0
// 1
// 12

Categories:

Updated:

Leave a comment