JavaScript中的空值合并运算符 [英] Nullish Coalescing operator in JavaScript
问题描述
如何更好地处理这个问题.
How to this thing in better way.
this.state.updateItem?this.state.updateItem.unit:'Unit';
我已经尝试过this.state.updateItem.unit || 'Unit',但是发现由于this.state.updateItem为NULL会产生错误,因此找不到unit的任何属性.
I have tried with this.state.updateItem.unit || 'Unit', but it found out that it will produce error since this.state.updateItem is NULL then it can't find any property of unit.
如何更好地做到这一点?
How to do it in better way?
推荐答案
现在您必须这样做:
(this.state.updateItem || {}).unit || 'Unit'
ES(JavaScript)针对可选链接的第一阶段提案我们(最终,希望如此)将能够执行以下操作:
There is a stage one proposal to ES (JavaScript) for optional chaining whereby we'll (eventually, hopefully) be able do do something like this:
this.state.updateItem?.unit || 'Unit'
如果您正在做通天塔,您现在就可以使用它!:
https://www.npmjs.com/package/babel-plugin-转换可选链
And if you're doing babel you can use it now!:
https://www.npmjs.com/package/babel-plugin-transform-optional-chaining
该提案现在处于第4阶段(截至2020年1月),并将被添加到JavaScript标准中
The proposal is now in stage 4 (as of January 2020) and will be added into the JavaScript standard
这篇关于JavaScript中的空值合并运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!