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

标签 javascript boolean ternary-operator

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/

相关文章:

javascript - jQuery - 在执行函数之前创建第一个动态页面

haskell - 理解 Haskell 的 Bool 推导 Ord

C 测验有 2 个问题不起作用?

c# - 为什么在三元运算符中分配 null 失败 : no implicit conversion between null and int?

PHP 多个三元运算符未按预期工作

javascript - 当 Mocha 测试失败时,它会将一个对象记录到控制台

javascript - 如何处理从 Node Express 重定向到 React Client 的身份验证(react-router-dom 和 useContext)

javascript - 对父组件的异步函数调用

java - boolean 值计算不正确?

python - 应用于三元运算符参数的一元运算符的用法(例如应用于字符串的 * 运算符参数)