为什么这段代码没有按预期工作?

why this code is not working as expected?

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 中 'if' 语句背后的底层代码。它依赖于将 if 语句的条件转换为布尔值的方法 'ToBoolean'。任何不为空的字符串都将转换为 true。因此,为什么你得到上述逻辑。