链判断运算符 ?.

function doSomething(onContent, onError) {
  try {
    // ... do something with the data 
  }
  catch (err) {
    if (onError) { // 校验onError是否真的存在
      onError(err.message);
    }
  }
}
// 使用可选链进行函数调用
function doSomething(onContent, onError) {
  try {
   // ... do something with the data
  }
  catch (err) {
    onError?.(err.message); // 如果onError是undefined也不会有异常
  }
}

  

const firstName = (message
  && message.body
  && message.body.user
  && message.body.user.firstName) || 'default';
const firstName = message?.body?.user?.firstName || 'default';

  

猜你喜欢

转载自www.cnblogs.com/blogZhao/p/12561188.html