tih*_*hom 31 javascript ruby ruby-on-rails
在Rails中我可以这样做:
x = user.try(:name)
Run Code Online (Sandbox Code Playgroud)
nil
如果user
是nil
else,则此方法返回user.name
.这name
是在user
对象上定义的方法.
我知道它可以if..then..else
在Javascript中使用但是有一个等效的紧凑方法在Javascript中做同样的事情吗?
谷歌搜索指向Javascript的try
命令,这不是我要找的.
PSL*_*PSL 42
你可以这样做,因为没有内置的方法:
var x = (user || {}).name;
Run Code Online (Sandbox Code Playgroud)
如果未定义用户(null),则不会破坏脚本.
但是必须在范围内的某个位置声明用户变量,即使其值未定义.否则你会得到错误的说用户没有定义.
类似地,如果在全局范围内,则可以显式检查此变量作为全局范围的属性,以避免上述错误
例如:
var x = (window.user || {}).name; // or var x = (global.user || {}).name;
Run Code Online (Sandbox Code Playgroud)
为了安全执行功能,
var noop = function(){}; //Just a no operation function
(windowOrSomeObj.exec || noop)(); //Even if there is no property with the name `exec` exists in the object, it will still not fail and you can avoid a check. However this is just a truthy check so you may want to use it only if you are sure the property if exists on the object will be a function.
Run Code Online (Sandbox Code Playgroud)
您可以使用逻辑AND(&&
)运算符.它的工作方式与大多数语言不同,因为它的结果不是布尔值.例如:
const x = user && user.name;
Run Code Online (Sandbox Code Playgroud)
下表显示了使用此运算符的所有可能结果:
+--------------+-----------------------+
| user | x = user && user.name |
+--------------+-----------------------+
| undefined | undefined |
| null | null |
| {} | undefined |
| {name:''} | '' |
| {name:'Jon'} | 'Jon' |
+--------------+-----------------------+
Run Code Online (Sandbox Code Playgroud)
它处于早期阶段,但我们可以开始使用它与babel.
这就是问题:
const person = {name: 'santiago'}
let zip = person.address.zip // Cannot read property 'zip' of undefined
Run Code Online (Sandbox Code Playgroud)
这是它的工作原理:
const person = {name: 'santiago'}
let zip = person?.address?.zip // undefined
Run Code Online (Sandbox Code Playgroud)
要开始使用它,我们需要babel alpha 7:
npm install --save-dev babel-cli@7.0.0-alpha.19
npm install --save-dev babel-plugin-transform-optional-chaining@^7.0.0-alpha.13.1
Run Code Online (Sandbox Code Playgroud)
我们需要将插件添加到我们的.babelrc中
{
"plugins": ["transform-optional-chaining"]
}
Run Code Online (Sandbox Code Playgroud)
Adam Bene Medium Post解释了如何使用它和另一个用例