为什么使用 || 时 'Unexpected "."'括号中默认值的运算符

Why 'Unexpected "."' when using || operator for a default value in parenthesis

出乎意料的“。”来自 jslint ( http://jslint.com/ ) 的代码:

function test(foo) {
    "use strict";
    return (foo || "").replace("bar", "baz");
}

为什么jslint的||有问题运算符强制一个空字符串,以便可以在不导致错误的情况下执行替换,以防 foo 作为未定义传递?

这通过了:

function test(foo) {
    "use strict";
    var xFoo = (foo || "");
    return xFoo.replace("bar", "baz");
}

我知道它是基于意见的,我可以忽略它,等等...但试图理解为什么这样的链接不受欢迎。也了解 eshint,但我并不是要回避此消息,只是想了解原因。

似乎第一种方法更简洁明了,因为它不需要额外的变量 (xFoo)。

这两个函数在所有条件下都做完全相同的事情。

可能是因为它认为 (foo || "") 会计算为布尔表达式,所以像 false.replace() 这样的东西是没有意义的。尽管,是的,在您的情况下,您得到的是一个变量或空字符串。

使用 String() contructor 删除 jslint

处的错误
function test(foo) {
    "use strict";
    return String(foo || "").replace("bar", "baz");
}

另见 Distinction between string primitives and String objects , JSLint Help

你可以只写成两行。

function test(foo) {
    "use strict";
    foo = foo || "";
    return foo.replace("bar", "baz");
}

无需创建临时 xFoo 变量。 foo 参数是自 JavaScript does not support passing-by-reference.

以来传入的参数的副本

看起来你在这里试图做的是提供一个默认参数。在那种情况下,我会通过更加明确和类型检查来crystal清楚你在做什么:

function test(foo) {
    "use strict";
    if (foo === undefined) {
      foo = "";
    }
    return foo.replace("bar", "baz");
}

是的,它不那么简洁,但它会减少代码的意图被后来阅读它的人误解的空间。显式检查类型还可以让您处理其他潜在问题。

function test(foo) {
    "use strict";
    if (foo === undefined) {
      foo = "";
    } else if (typeof foo !== 'string') {
      throw('foo must be a string');
    }
    return foo.replace("bar", "baz");
}

如果你使用的是 ES2015,你也可以使用 default parameter:

function test(foo = "") {
    "use strict";
    if (typeof foo !== 'string') {
      throw('foo must be a string');
    }
    return foo.replace("bar", "baz");
}

对于几乎所有项目,我建议添加 Babel to your build process so you can use default parameters and the many other 有用的功能 ES2015 添加到语言中。使用 Babel 可以让您现在就可以使用它们,而不必等待所有浏览器都实现它们。