我对如何评估truthy或falsy值的角度有点困惑。显然,当我直接以有棱角的方式做以下事情时,事情就会起作用。
if (0) { console.log('not printed'); }
else { console.log('printed'); }
if (1) { console.log('printed'); }
else { console.log('not printed'); }
但是,如果我从模板中将值传递给我的控制器......那么事情就不起作用了。为什么呢?
function (someValue) {
if (someValue) { console.log('always printed whether someValue is 0 or 1'); }
else { console.log('not printed'); }
...
答案 0 :(得分:0)
比较时,js中存在松散相等和严格相等。如果该值不是Boolean
的类型,则会转换为true
或false
if (someValue === '0' || someValue === '1') {
console.log('always printed whether someValue is 0 or 1');
}
else {
console.log('not printed');
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
Implicit data type conversion in JavaScript when comparing integer with string using ==
答案 1 :(得分:0)
请勿在{{1}}语句中使用0
和1
。因为在javascript中使用try if
和'0'
作为字符串或设置其他一些标志来克服这个问题是很困惑的。
答案 2 :(得分:0)
通常我使用全局函数来推导truthy
值。
function truthy(val){
switch(typeof val){
case "number":
// since the val is already a number, only zero and NaN should be counted as falsy.
return val !== 0 && !Number.isNaN(Number(val));
case "string":
// val is string, so need to check if its empty or "0". Otherwise it should be counted as truthy
return val !== "" && val !== "0";
case "boolean":
// val is already boolean so only boolean check would suffice
return val === true;
case "symbol":
// symbol should be truthy
return true;
case "object":
// object can be deceiving, so lets check for NULL and empty object
if( val === null ){
return false;
}
else{
for( var i in val ){
if( val.hasOwnProperty(i) ){
return true;
}
}
}
return false;
case "undefiend":
return false;
case "function":
return true;
}
}
function falsy(val){
return !truthy(val);
}
console.log(truthy(1)); // should be true
console.log(truthy(0)); // should be false
console.log(truthy(NaN)); // should be false
console.log(truthy("")); // should be false
console.log(truthy("0")); // should be false
console.log(truthy("1")); // should be true
console.log(truthy("meh")); // should be true
console.log(truthy({})); // should be false
console.log(truthy(null)); // should be false
console.log(truthy(false)); // should be false