简体   繁体   English

javascript:令人惊讶的操作顺序

[英]javascript: surprising order of operations

I recently wrote code that didnt work as i would expect, it was: 我最近编写的代码没有像我期望的那样工作,它是:

message = 'Thank You';
type = 'success';

message = message || type == 'success' ? 'Success' : 'Error';

It was news to me that at the end of that message was set to 'Success' . 对我来说, message的结尾是“成功”

I would think that since the truthy value of message is true , the right side of the or would not evaluate. 我认为,既然消息的true价值是true ,那么右边or 不会评价。

Parenthesis around the right side of the OR solved this, but i still dont understand why the right side was evaluated at all OR右侧的括号解决了这个问题,但我仍然不明白为什么右侧进行了评估

Your code is equivalent to 你的代码相当于

message = ( message || type == 'success' ) ? 'Success' : 'Error';

That's why. 这就是为什么。 :) :)

The value of message doesn't end up as "success" but "Success" . message的价值不会以"success"而是"Success"

The ? ? operator has lower precedence than the || 运算符的优先级低于|| operator, so the code is evaluated as: 运算符,因此代码被评估为:

message = (message || type == 'success') ? 'Success' : 'Error';

The result of message || type == 'success' message || type == 'success'的结果 message || type == 'success' will be "Thank You" , and when that is evaluated as a boolean for the ? message || type == 'success'将是"Thank You" ,当它被评估为?的布尔值? operator, the result is true . 运算符,结果是true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM