简体   繁体   English

最佳替代var x = y || 假

[英]Best replacement for var x = y || false

A codebase I'm working on contains many uses of the javascript 'default operator' such as: 我正在处理的代码库包含javascript“默认运算符”的许多用法,例如:

var x = y || false;

I'm wondering what the best possible replacement to use in order to guarantee that the value is never undefined, null, etc. Should I replace them with "false" and check against the string? 我想知道最好使用什么替换来保证值永远不会是undefined,null等。我应该将它们替换为“ false”并检查字符串吗? Should I replace them with their longhand counterpart (explicit checks for null and undefined)? 我应该用它们的长期对应替换它们吗(显式检查null和undefined)? Or does each use case need to be evaluated for something I'm not taking into account? 还是需要针对每个用例针对我没有考虑的因素进行评估?

To set a non-falsy default when your input could be a valid falsy value, one way is to do two tests 要在输入可能是有效的伪造值时设置非伪造的默认值,一种方法是进行两次测试

if (!x && x !== 0) {
    x = 1; // 1 is the default value but 0 is a valid input
}

The advantage of doing it like this is you can exclude non-valid falsy values, eg NaN 这样做的好处是您可以排除无效的伪造值,例如NaN


This said, you may be better off casting or type checking 话虽如此,您最好不要进行类型转换或类型检查

if (typeof x !== 'number') x = 1;

or 要么

x = +x;
if (x !== x) x = 1; // NaN goes to default

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

相关问题 var x,y ='foo';这可以实现吗? - var x, y = 'foo'; Can this be accomplished? jQuery 源代码中的奇怪代码: var !== var ? x : y; - Strange code in jQuery sources: var !== var ? x : y; JavaScript-有没有办法以数组形式存储“ var x === var y”和“ var c === var”之类的东西 - JavaScript - Is there a way to store things like “var x === var y” and “var c === var” in an array form 在 JavaScript var x=2,var y=“2”; console.log(xy),为什么 o/p 为 0? - In JavaScript var x=2, var y=“2”; console.log(x-y), why is o/p 0? 将`if(x = y)`永远返回false或者在JavaScript中失败? - Will `if(x=y)` Ever Return false, or fail In JavaScript? 假= =(x&gt; y)如何工作? - How does false == (x > y) work? for(var x in array)和for(var x = 0,y = array.length; x之间的性能差异 - Performance's difference between for (var x in array) and for (var x=0, y= array.length; x<y; x++) 那个js表达式是否安全:if(!x || doSomething(x [prop],y [prop])=== false) - Is that js expression safe: if( !x || doSomething( x[prop], y[prop] ) === false ) 如果 X 为真,则执行此操作,但如果 X 为真且 Y 为假,请执行此操作 - If X is true then do this but if X is true & Y is false do this 在javascript中设置1行中的多个变量是否有效? (var x = y ='value';) - Is setting multiple variables in 1 line valid in javascript? (var x=y='value';)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM