可以判断前面的变量是否为 null 或 undefined,若不为空再执行后面
早知道这个,我哪还用写那么多的判断啊!😂😂😂😂😂😂😂
?.
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
},
eat() {
return 'apple';
}
};
const catName = adventurer.cat?.name;
// expected output: "Dinah"
const dogName = adventurer.dog?.name;
// expected output: undefined
const food = adventurer.eat?.();
// expected output: "apple"
const words = adventurer.talk?.();
// expected output: undefined
//------------------------多个条件----------------------------------
function getLeadingActor(movie) {
return movie.actors?.[0]?.name;
}
getLeadingActor(movieSmall); // => undefined
getLeadingActor(movieFull); // => 'Harrison Ford'
?? nullish 合并
名为 nullish coalescing operator 的新提案建议用 ?? 处理 undefined或null,将它们默认为特定的值。
如果 variable 是undefined或null,则表达式 variable ?? defaultValue 的结果为defaultValue, 否则表达式的值为variable 的值。
const noValue = undefined;
const value = 'Hello';
noValue ?? 'Nothing'; // => 'Nothing'
value ?? 'Nothing'; // => 'Hello'
function getLeadingActor(movie) {
return movie.actors?.[0]?.name ?? 'Unknown actor';
}
getLeadingActor(movieSmall); // => 'Unknown actor'
getLeadingActor(movieFull); // => 'Harrison Ford'
### optional chaining 的 3 种形式
第一种形式 object?.property 用于访问静态属性:
const object = null;
object?.property; // => undefined
第二种形式 object?.[expression] 用于访问动态属性或数组项:
const object = null;
const name = 'property';
object?.[name]; // => undefined
const array = null;
array?.[0]; // => undefined
最后,第三种形式 object?.([arg1,[arg2,...]]) 执行一个对象方法:
const object = null;
object?.method('Some value'); // => undefined