Javascript 为什么真值或假值在角度控制器中不起作用?
我有点困惑,在角度上如何评估真实值或虚假值。显然,当我直接在角上做以下事情时。。。事情是这样的Javascript 为什么真值或假值在角度控制器中不起作用?,javascript,angularjs,variables,Javascript,Angularjs,Variables,我有点困惑,在角度上如何评估真实值或虚假值。显然,当我直接在角上做以下事情时。。。事情是这样的 if (0) { console.log('not printed'); } else { console.log('printed'); } if (1) { console.log('printed'); } else { console.log('not printed'); } 但是,如果我从模板向控制器传递一个值。。。然后事情就不起作用了。为什么? function (someValue
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'); }
...
比较起来,js中有松散相等和严格相等。如果该值不是布尔类型,则将转换为true或false
通常,我使用全局函数来推导真实值
您确定someValue不是字符串0吗?是的,它是字符串!好吧,我明白了。所以这毕竟与角度无关。。。。常规javascript也会有相同的结果?在javascript中使用0和1表示true和false非常容易出错。是的!!例如,控制台中的0提供了true。是的,常规JS也会有相同的效果。0与0不同/为空/未定义。
if (someValue === '0' || someValue === '1') {
console.log('always printed whether someValue is 0 or 1');
}
else {
console.log('not printed');
}
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