得到意想不到的“。”来自 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()
contructor 消除 jslint 的错误
function test(foo) {
"use strict";
return String(foo || "").replace("bar", "baz");
}
另见 Distinction between string primitives and String objects , JSLint Help
关于javascript - 为什么使用||时 'Unexpected "."'括号中默认值的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34845898/