你如何在 JavaScript 中实现一个保护子句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5339121/
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-10-25 16:52:30  来源:igfitidea点击:

How do you implement a guard clause in JavaScript?

javascriptundefined

提问by luebken

I want to guard my functions against null-ish values and only continue if there is "defined" value.

我想保护我的函数免受空值的影响,并且只有在有“定义”值时才继续。

After lookingaroundthe solutions suggested to double equal to undefined: if (something == undefined). The problem with this solution is that you can declare an undefined variable.

之后周围的解决方案,建议增加一倍等于未定义:if (something == undefined)。此解决方案的问题在于您可以声明未定义的变量。

So my current solution is to check for null if(something == null)which implicetly checks for undefined. And if I want to catch addionalty falsy values I check if(something).

所以我目前的解决方案是检查 nullif(something == null)隐式检查未定义。如果我想捕捉额外的虚假值,我会检查if(something).

See tests here: http://jsfiddle.net/AV47T/2/

在这里查看测试:http: //jsfiddle.net/AV47T/2/

Now am I missing something here?

现在我在这里错过了什么吗?

Matthias

马蒂亚斯

回答by Travis Webb

The standard JS guard is:

标准的 JS 守卫是:

if (!x) {
    // throw error
}

!xwill catch any undefined, null, false, 0, or empty string.

!x将捕获任何undefined, null, false, 0, 或空字符串。

If you want to check if a value is valid, then you can do this:

如果你想检查一个值是否有效,那么你可以这样做:

if (Boolean(x)) {
    // great success
}

In this piece, the block is executed if x is anything butundefined, null, false, 0, or empty string.

在这一块,如果x是任何执行该块,但undefinednullfalse0,或空字符串。

-tjw

-tjw

回答by Shadow Wizard is Ear For You

The only safe way that I know ofto guard against reallyundefined variables (meaning having variable name that were never defined anywhere) is check the typeof:

我所知道的防止真正未定义的变量(意味着从未在任何地方定义过变量名)的唯一安全方法是检查typeof

if (typeof _someUndefinedVarName == "undefined") {
   alert("undefined");
   return;
}

Anything else (including if (!_someUndefinedVarName)) will fail.

其他任何东西(包括if (!_someUndefinedVarName))都会失败。

Basic example: http://jsfiddle.net/yahavbr/Cg23P/

基本示例:http: //jsfiddle.net/yahavbr/Cg23P/

Remove the first block and you'll get:

删除第一个块,你会得到:

_someUndefinedVarName is not defined

_someUndefinedVarName 未定义

回答by Rich

Only recently discovered using '&&' as a guard operator in JS. No more If statements!

最近才发现在 JS 中使用“&&”作为保护运算符。没有更多的 If 语句!

var data = {
  person: {
    age: 22,
    name: null
  }
};

var name = data.person.name && doSomethingWithName(data.person.name);

回答by Arnaud Debray

Ternary to the rescue !

三元来救援!

(i) => 
    i == 0 ? 1 :
    i == 1 ? 2 :
    i == 2 ? 3 :
    null