网络编程 
首页 > 网络编程 > 浏览文章

ES2020让代码更优美的运算符 (?.) (??)

(编辑:jimmy 日期: 2024/6/16 浏览:3 次 )

链判断运算符("htmlcode">
// error
const firstName = message.body.user.firstName;

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

也可以用三元运算符"htmlcode">

const fooInput = myForm.querySelector('input[name=foo]')
const fooValue = fooInput "htmlcode">
const firstName = message"htmlcode">
"#C0FFEE".match(/#([A-Z]+)/i)"htmlcode">
a"htmlcode">
delete a"htmlcode">
(a"htmlcode">
// 构造函数
new a"htmlcode">
const headerText = response.settings.headerText || 'Hello, world!';
const animationDuration = response.settings.animationDuration || 300;
const showSplashScreen = response.settings.showSplashScreen || true;

上面的三行代码都通过||运算符指定默认值,属性的值如果为''或false或0,默认值也会生效。

为了避免这种情况,ES2020 引入了一个新的 Null 判断运算符"htmlcode">

const headerText = response.settings.headerText "htmlcode">
const animationDuration = response.settings"htmlcode">
function Component(props) {
 const enable = props"htmlcode">
// 报错
lhs && middle "htmlcode">
(lhs && middle) ?? rhs;
lhs && (middle ?? rhs);

(lhs ?? middle) && rhs;
lhs ?? (middle && rhs);

(lhs || middle) ?? rhs;
lhs || (middle ?? rhs);

(lhs ?? middle) || rhs;
lhs ?? (middle || rhs);

ES版本更新的福利

在几个月前的腾讯开发者大会上,有位热心市民向ES开发者请教了这个问题,刚好借这篇文章的话题,在这里分享给大家!

关于ES版本更新,为什么ES5到ES6是大幅度书籍式的更新,此后版本更新只新增稀少的几个新技术?

原因:“怕你们学不动!”

其实,前者的更新方式,要学那么多东西,那么厚的一本天书,会给人一种望而却步的感觉,还没进门就先跪了。

后者来说,只是几个新技术,可能半天一天的,就能完全掌握并大结局了,收获的成就感会更多更快!

上一篇:element-ui封装一个Table模板组件的示例
下一篇:详解阿里Node.js技术文档之process模块学习指南
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。