通过逻辑运算符分配默认值 [英] Assigning a default value through the logical operator OR

查看:110
本文介绍了通过逻辑运算符分配默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道javascript逻辑运算符||如果第一个操作数为 true ,则产生其第一个操作数的值。否则,它将产生第二个操作数的值。

We know that the javascript logical operator || produces the value of its first operand if the first operand is true. Otherwise, it produces the value of the second operand.

因此在此示例中:

<script language="javascript">
function test (value){
    this.value = value || "(value not given)";
}
</script>

如果传递给函数的参数 value 被视为 false ,例如整数 0 或空字符串 ,则 this.value 将设置为( value not 这是不正确的(因为我们确实传递了一个值)。

if the parameter value passed to the function is treated as false like the integer 0 or the empty string "" then this.value will be set to (value not given) which is not true correct (because indeed we are passing a value).

所以问题是设置 this.value 的最佳方法?

So the question is which should be the best way to set this.value?

编辑:所有4个第一个答案都使用三元运算符? 。我的问题是关于 ||的

EDIT: All 4 first answers use the ternary operator "?". My question is about "||" operator.

推荐答案

使用 || 的方案最方便写入,但仅当错误值(未定义 0 false NaN )不是合法值。 (当您只想处理 null undefined 时,可以使用新的空值合并运算符( ?? )在此提案中描述了 ,并且

The scheme with || is the most convenient to write, but it can ONLY be used when a falsey value (undefined, null, 0, "", false, NaN) is not a legitimate value. (When you just want to deal with null and undefined, you can use the new nullish coalescing operator (??) described in this proposal and included in ES2020.)

如果您想允许特定的false值而不允许其他值,则必须编写更特定的代码来处理特定情况。例如,如果您想允许一个空字符串,但不允许null或undefined或其他false值,则必须编写更具体的代码,如下所示:

If you want to allow specific falsey values and not allow others, then you have to write more specific code to handle your specific cases. For example, if you wanted to allow an empty string, but not allow null or undefined or other falsey values, then you'd have to write more specific code like this:

function test(value) {
    if (value || value === "") {
        this.value = value;
    } else {
        this.value = "(value not given)";
    }
}

或者如果您只想排除 undefined ,您可以专门对其进行测试:

Or if you only want to exclude only undefined, you can test for it specifically:

function test(value) {
    if (value === undefined) {
        value = "(value not given)";
    }
    this.value = value;
}

这篇关于通过逻辑运算符分配默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆