let x;
console.log("shubham" == true ); // gives false
"shubham" ? x=2 : x=3;
console.log(x); // gives 2, so "shubham" must be true?
//我希望得到值3
最佳答案
当你使用它时:
"shubham" == true
比较前,true变为1,所以实际比较是
"shubham" == 1
所以,它给出了错误;
这本书:
When performing conversions, the equal and not-equal operators follow these basic rules:
If an operand is a Boolean value, convert it into a numeric value before checking for equality. A value of false converts to 0, whereas a value of true converts to 1.
If one operand is a string and the other is a number, attempt to convert the string into a number before checking for equality.
当你使用它时:
"shubham" ? x=2 : x=3;
工作方式如下:
Boolean("shubham")?x=2:x=3
所以,它给你 x=2;
这本书:
variable = boolean_expression ? true_value : false_value;
This basically allows a conditional assignment to a variable depending on the evaluation of the boolean_expression. If it’s true, then true_value is assigned to the variable; if it’s false, then false_value is assigned to the variable.
这本书:
Professional JavaScript for Web Developers.3rd.Edition.Jan.2012
关于javascript - 为什么这段代码没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48717122/