es6新增的运算符-链判断运算符的诞生[?.]和null的判断运算符??

  • es6新增的运算符-链判断运算符的诞生[?.]和null的判断运算符??已关闭评论
  • 198 次浏览
  • A+
所属分类:Web前端

指数运算符 **

console.log(2 ** 2 ) //4 console.log(2 ** 3 ) //8 console.log(2 ** 4) //16 

链判断运算符的诞生(?.)

在实际编程中, 如果读取对象内部的某个属性,往往需要判断一下。 属性的上层对象是否存在。比如,读取 message.body.user.firstName这个属性,安全的写法是写成下面这样。  let message={   body:{      user:{   	firstName:''      }   } } 			 // 错误的写法;因为这message.body这个值可能没有,会导致报错 const  firstName = message.body.user.firstName || 'default';  // 正确的写法 const firstName = (message   && message.body   && message.body.user   && message.body.user.firstName) || 'default'; 有的小伙伴可能会觉得这样会很麻烦,怎么会处理这个问题了。   //使用链式运算符 let myDefault= message?.body?.user?.firstName || '默认值'; /**  * 上面代码中,如果message是null或undefined,  * 或者message.body是null或undefined,  * 或者message.body.user是null或undefined,  * 或者message.body.user.firstName是null或undefined.  * 就会返回--默认值。  * */  

链判断运算符(?.)的详细讲解

?.运算符,直接在链式调用的时候判断。 左侧的对象是否为null或undefined。 如果是的,就不再往下运算,而是返回undefined 本质上,?.运算符相当于一种短路机制,只要不满足条件,就不再往下执行。 

链判断运算符-判断对象是否有某个方法

let message={ // say:function(){ //    console.log('hello word') // } } //如果没有该方法,则不会被执行的哈 message.say?.()   //返回undefined console.log(message.say?.()) 

Null 判断运算符 ( ?? )

读取对象属性的时候,如果某个属性的值是null或undefined, 有时候需要为它们指定默认值。常见做法是通过||运算符指定默认值。 const headerText = response.settings || 'Hello, world!'; const animationDuration = response.settings || 300; 但是我们开发者的意愿是: 只要属性的值为null或undefined,默认值就会生效, 但是实际属性的值如果为空字符串或false或0,默认值也会生效。(与我们的初衷相违背)  为了避免这种情况,ES2020 引入了一个新的 Null 判断运算符??。 它的行为类似||,但是只有运算符左侧的值为null或undefined时,才会返回右侧的值。  const headerText = response.settings ?? 'Hello, world!'; const animationDuration = response.settings ?? 300; 上面代码中,默认值只有在左侧属性值为null或undefined时,才会生效。  const animationDuration = response.settings?. animationDuration ?? 300; 上面代码中, 如果response.settings是null或undefined, 或者response.settings.animationDuration是null或undefined, 就会返回默认值300。 也就是说,这一行代码包括了两级属性的判断。