简体   繁体   English

JavaScript中的字符串括号

[英]Parentheses around string in JavaScript

I was reading Marionette's source code and I came across something like: 我正在阅读Marionette的源代码 ,我遇到了类似的东西:

if (_.isObject(message)) {
    message = (
      message.prev + ' is going to be removed in the future. ' +
      'Please use ' + message.next + ' instead.' +
      (message.url ? ' See: ' + message.url : '')
    );
}

Why exactly is message wrapped in parentheses? 为什么message包含在括号中? What does that do? 那是做什么的?

In this specific example, the outer parentheses do not serve any function, other than (arguably) improving readability. 在该具体示例中,除了(可以说)提高可读性之外,外括号不提供任何功能。

This code is functionally identical: 此代码功能相同:

if (_.isObject(message)) {
    message = 
        message.prev + ' is going to be removed in the future. ' +
        'Please use ' + message.next + ' instead.' +
        (message.url ? ' See: ' + message.url : '');
}

The parentheses around the ternary operator are added so the ternary operator doesn't evaluate everything before the message.url . 添加了三元运算符周围的括号,因此三元运算符不会在message.url之前计算所有内容。

I don't think the outer-most does anything. 我不认为外面做任何事情。 Probably the author used it for readability reasons. 可能是作者出于可读性原因使用它。 The inner is needed for the conditional (?) operator. 条件(?)运算符需要内部。

It's mainly for readability. 这主要是为了提高可读性。
With or without, the functionality does not change. 无论有没有,功能都不会改变。

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

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