为什么'意外'。''使用时||括号

时间:2016-01-18 01:21:18

标签: javascript jslint

意外“。”来自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)。

在所有条件下,两个函数都完全相同。

3 个答案:

答案 0 :(得分:1)

可能是因为它认为(foo || "")将评估为布尔表达式,因此像false.replace()这样的东西没有意义。即使如此,在你的情况下,你会得到一个变量或空字符串。

答案 1 :(得分:1)

使用String() 构造函数会删除jslint错误

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

另请参阅Distinction between string primitives and String objectsJSLint Help

答案 2 :(得分:1)

你可以把它分成两行。

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

无需创建临时xFoo变量。 foo参数是自JavaScript does not support passing-by-reference以来传递的参数的副本。

看起来你在这里尝试做的是提供一个默认参数。在这种情况下,我会通过更明确地对其进行类型检查来清楚地说明你正在做什么:

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添加到您的构建过程中,这样您就可以使用默认参数和ES2015添加到语言中的many other有用功能。使用Babel允许您现在使用它们,而无需等待所有浏览器实现它们。