简体   繁体   English

在javascript函数中为布尔参数设置默认值

[英]Set a default value for a boolean parameter in a javascript function

I have used typeof foo !== 'undefined' to test optional parameters in javascript functions, but if I want this value to be true or false every time, what is the simplest or quickest or most thorough way? 我已经使用了typeof foo !== 'undefined'来测试javascript函数中的可选参数,但是如果我希望每次都使这个值为truefalse ,那么最简单或最快或最彻底的方法是什么? It seems like it could be simpler than this: 看起来它可能比这更简单:

function logBool(x) {
    x = typeof x !== 'undefined' && x ? true : false;
    console.log(x);
}

var a, b = false, c = true;
logBool(a); // false
logBool(b); // false
logBool(c); // true

You could skip the ternary, and evaluate the "not not x", eg !!x . 你可以跳过三元组,并评估“not not x”,例如!!x

If x is undefined, !x is true, so !!x becomes false again. 如果x未定义,则!x为真,所以!!x再次变为false。 If x is true, !x is false so !!x is true. 如果x为真,则!x为假,所以!!x为真。

function logBool(x) {
    x = !!x;
    console.log(x);
}

var a, b = false, c = true;
logBool(a); // false
logBool(b); // false
logBool(c); // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM