为什么使用时出现“意外的”.“||运算符,以表示括号中的默认值

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

本文关键字:运算符 表示 默认值 意外的 为什么 意外      更新时间:2023-09-26

Get Unexpected "." 来自 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)。

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

使用String()构造器可以消除 jslint 上的错误

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

另请参阅字符串基元和字符串对象之间的区别 , JSLint 帮助

这可能是

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

你可以

把它变成两行。

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

无需创建临时xFoo变量。 foo 参数是传入的参数的副本,因为 JavaScript 不支持按引用传递。

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

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,您还可以使用默认参数:

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

对于几乎任何项目,我建议将 Babel 添加到您的构建过程中,以便您可以使用默认参数和 ES2015 添加到语言中的许多其他有用功能。 使用 Babel 可以让你现在使用它们,而不必等待所有浏览器实现它们。