Assigning a default value through the logical operator OR

心已入冬 提交于 2020-07-29 21:56:06

问题


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.

So in this example:

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

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).

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

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


回答1:


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.)

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)";
    }
}

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;
}



回答2:


It depends on what values you want to exclude. If the "general false values" are too broad of a category, you can be more explicit:

function test(value) {
    this.value = value !== undefined ? value : "(value not given)";
}



回答3:


If you want to be able to assign falsey values do this.

this.value = (typeof value !== 'undefined') ? value : 'value not given';

This will retain values like false, '', and 0, but will use the default when the value is actually not passed as a parameter.




回答4:


<script language="javascript">
function test (value){
    this.value = arguments.length > 0 ? value : "(value not given)";
}
</script>

You can check to see if that argument was passed in by checking that functions arguments array's length.




回答5:


The correct way is:

this.value = (typeof value == 'undefined') ? 'my argument' : value;

Probably duplicate question. Google it.



来源:https://stackoverflow.com/questions/8156855/assigning-a-default-value-through-the-logical-operator-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!