1.?.(선택적 체인 연산자)
JavaScript에서 "?."는 "Optional Chaining"이라는 새로운 연산자입니다. 이를 통해 null이거나 정의되지 않은 속성에 액세스하거나 존재하지 않는 메서드를 호출할 때 오류를 방지할 수 있습니다.
?.연산자를 사용하면 오류를 일으키거나 프로그램 실행을 중단시키지 않고 객체의 속성과 메서드에 안전하게 액세스할 수 있습니다. 객체의 속성이나 메서드가 존재하지 않는 경우 표현식은 TypeError 예외를 발생시키는 대신 정의되지 않은 값을 반환합니다.
1.1 객체 속성에 접근
const person = {
name: 'John',
address: {
city: 'New York'
}
};
console.log(person.address?.city); // 输出:'New York'
// 输出:undefined,因为person对象没有age属性
console.log(person.age?.toString());
1.2 객체 메소드 호출
const calculator = {
add: function(a, b) {
return a + b;
}
};
console.log(calculator.add?.(2, 3)); // 输出:5
// 输出:undefined,因为calculator对象没有subtract方法
console.log(calculator.subtract?.(5, 2));
1.3 체인 사용법?.
const user = {
profile: {
name: 'Alice',
email: '[email protected]'
}
};
console.log(user?.profile?.name); // 输出:'Alice'
// 输出:undefined,因为user对象没有address属性
console.log(user?.address?.city);
지침:
- ?. 연산자를 사용할 때 대상 속성이나 메서드가 존재하고 호출 가능한 경우 정상적으로 실행됩니다.
- 대상이 null이거나 정의되지 않은 경우 표현식은 즉시 정의되지 않은 값을 반환하고 후속 속성이나 메서드에 액세스하려는 더 이상 시도가 이루어지지 않습니다.
- 연산자는 [](대괄호)와 함께 사용할 수 없습니다. 예를 들어 obj?.[index]는 잘못된 구문입니다.
2. ??(널 값 병합 연산자)
JavaScript에서 "??"는 null 값 병합 연산자를 사용하는 것입니다. 표현식이 null인지 정의되지 않았는지 확인하고 기본값을 반환하는 데 사용됩니다.
const name = null;
/*
使用??运算符来判断name的值是否为空,如果为空,则赋予默认值"Unknown"
*/
const displayName = name ?? "Unknown";
console.log(displayName); // 输出: Unknown
/*
经常在表格或者数据渲染时可以用到,当表格数据为空时,直接显示 -
const data = null?? '-'
*/