Javascript 是否可以在javascript中检查内联空值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48341869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:04:55  来源:igfitidea点击:

Is it possible to check for null inline in javascript?

javascriptnull

提问by darkermuffin

I have a function which parses the address components of the Google Maps API JSONand then returns the city / locality / route name.

我有一个函数可以解析 Google Maps API 的地址组件, JSON然后返回城市/地点/路线名称。

The getAddressComponent()returns a nullif it cannot find the key.

getAddressComponent()回报null,如果它不能找到问题的关键。

let route = getAddressComponent(addressComponents, 'route').value.long_name;

let route = getAddressComponent(addressComponents, 'route').value.long_name;

So let's say it didn't find the key, then I get a Error: TypeError: Cannot read property 'long_name' of undefinedobviously because it's not defined.

所以假设它没有找到密钥,然后我Error: TypeError: Cannot read property 'long_name' of undefined显然得到了一个,因为它没有定义。

How do I check for nullin javascript other than the conditional method (a === null)?

null除了条件方法之外,我如何在 javascript 中检查(a === null)

How can I simply check like this with ?

我怎么能简单地像这样检查 ?

EDIT : Safe Navigation Operator

编辑:安全导航操作员

let route = getAddressComponent(addressComponents, 'route')?.value.long_name;

let route = getAddressComponent(addressComponents, 'route')?.value.long_name;

And if it doesn't exists, it could probably set routeto nullinstead of throwing a Error ?

如果它不存在,它可能会设置routenull而不是抛出错误?

回答by Pac0

  • There is no "null-safe navigation operator" in Javascript(EcmaScript 5 or 6), like ?.in C#, Angular templates, etc. (also sometimes called Elvis operator, when written ?:) , at least yet, unfortunately.

  • You can test for nulland return some dependent expression in a single line with the ternary operator?:, as already given in other answers :

    (use === nullto check only for nulls values, and == nullto check for nullandundefined)

    console.log(myVar == null ? myVar.myProp : 'fallBackValue');
    
  • in some cases, like yours, when your variable is supposed to hold an object, you can simply use the fact that any object istruthywhereas nulland undefinedare falsyvalues :

    if (myVar) 
        console.log(myVar.myProp)
    else
        console.log('fallbackValue')
    

    You can test for falsy values by coalescing to boolean with !!and make this inline :

    console.log(!!myVar ? myVar.myProp : 'fallbackValue');
    

    Be very careful though with this "falsy test", for if your variable is 0, '', or NaN, then it is falsyas well, even though it is not null/undefined.

  • 不幸的是,Javascript(EcmaScript 5 或 6)中没有“空安全导航运算符”,就像?.C#、Angular 模板等(有时也称为 Elvis 运算符,在编写时?:)。

  • 您可以使用三元运算符null在一行中测试并返回一些依赖表达式,如其他答案中已经给出的:?:

    (用于=== null仅检查nulls 值,并== null检查nullundefined

    console.log(myVar == null ? myVar.myProp : 'fallBackValue');
    
  • 在某些情况下,像你这样的,当你的变量应该持有的object,你可以简单地用一个事实,即任何物体是truthy,而nullundefinedfalsy值:

    if (myVar) 
        console.log(myVar.myProp)
    else
        console.log('fallbackValue')
    

    您可以通过合并到 boolean with!!并使其内联来测试虚假值:

    console.log(!!myVar ? myVar.myProp : 'fallbackValue');
    

    尽管这个“假测试”要非常小心,因为如果你的变量是0, '', or NaN,那么它也是假的,即使它不是空/未定义。

回答by Nicolas Reynis

What you want is a null coalescent operator. Javascript doesn't have one. Most of the time peoples use the logical OR ||for this purpose but it doesn't work on property access.

你想要的是一个空合并运算符。Javascript 没有。大多数时候,人们||为此目的使用逻辑 OR ,但它不适用于属性访问。

There's proposal for adding null coalescing to the language, but it's nowhere near: https://github.com/tc39/proposal-nullish-coalescing
https://tc39.github.io/proposal-nullish-coalescing/

有向语言添加空值合并的建议,但离它很远:https: //github.com/tc39/proposal-nullish-coalescing
https://tc39.github.io/proposal-nullish-coalescing/

If you really, really, absolutly want to use it you can use this Babel plugin: https://www.npmjs.com/package/babel-plugin-transform-optional-chaining
But I would strongly suggest you don't: this may never make it to the language and you would have unvalid code in your codebase.

如果你真的,真的,绝对想使用它,你可以使用这个 Babel 插件:https: //www.npmjs.com/package/babel-plugin-transform-optional-chaining
但我强烈建议你不要:这个可能永远不会进入该语言,并且您的代码库中会有无效代码。

回答by zabusa

let component = getAddressComponent(addressComponents, 'route');
let route = component ? component : null

you can use the ?operator to check the value is trueor falsethen set the value in javascript nullwill be false

您可以使用?运算符检查值是truefalse然后在 javascript 中设置值null将是false

回答by ilkerkaran

Code below simplified return num ? num : 0for me:

下面的代码return num ? num : 0为我简化:

return num || 0;

return num || 0;

回答by KL_

For empty strings you can use !:

对于空字符串,您可以使用!

var foo = 'yo';
console.log(!foo);

var foo = null;
console.log(!foo);

And for the ?you asked about, it's the Conditional (ternary) Operator, the syntax is condition ? if true : if falseyou can use it as follows:

对于?您询问的,它是Conditional (ternary) Operator,语法是condition ? if true : if false您可以按如下方式使用它:

var foo = 'yo';
console.log('1 : ' + (!foo ? 'Null' : 'Not Null'));
console.log('2 : ' + (foo === null ? 'Null' : 'Not Null'));
console.log('3 : ' + (foo == null ? 'Null' : 'Not Null'));

var foo = null;
console.log('1 : ' + (!foo ? 'Null' : 'Not Null'));
console.log('2 : ' + (foo === null ? 'Null' : 'Not Null'));
console.log('3 : ' + (foo == null ? 'Null' : 'Not Null'));

回答by vanelizarov

.?cannot be used in javascript, for that, you might look into typescript.

.?不能在 javascript 中使用,为此,您可能会查看打字稿。

For example, you can use try...catchconstruction:

例如,您可以使用try...catch构造:

let route

try {
  route = getAddressComponent(addressComponents, 'route').value.long_name
} catch (error) {
  route = null
}