in 연산자는 명시된 속성이 명시된 객체에 의존하면 true
를 반환합니다.
속성(property) in 객체명(object)
반드시 in
연산자의 오른쪽에 객체
를 명시하여야 합니다.
// 배열
const trees = new Array("redwood", "bay", "cedar", "oak", "maple");
0 in trees // true (인덱스 0)
3 in trees // true (인덱스 3)
(1 + 2) in trees // true (인덱스 3)
6 in trees // false (인덱스 6은 존재하지 않습니다.)
"bay" in trees // false (배열의 내용이 아닌, 인덱스 값을 명시하여야 합니다.)
"length" in trees // true (length는 Array 객체의 속성입니다.)
// 사용자가 정의한 객체
const myCar = {company: "Lamborghini", model: "Lamborghini Veneno Roadster", year: 2014};
"company" in myCar // true를 반환합니다.
"model" in myCar // true를 반환합니다.
예컨대 string 생성자
로 만들어진 문자열을 명시할 수 있지만 문자열 리터럴
은 명시할 수 없습니다.
*color2.length
를 반환하면 값은 6으로 나옵니다. 하지만 in
연산자의 경우 객체
를 명시하여야 하기 때문에 TypeError
가 나타나게 됩니다.*
let color1 = new String("green");
"length" in color1 // true
let color2 = "yellow";
"length" in color2 // color2는 String 객체가 아니기게 오류를 냅니다.
// TypeError: Cannot use 'in' operator to search for 'length' in 'yellow'
let color2 = "yellow";
color2.length // 6
typeof color2 // 'string'
ref: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/in