构造 x = x || 是什么?你的意思是?
我正在调试一些 JavaScript,但无法解释这个 || 的作用:
I am debugging some JavaScript and can't explain what this || does:
function (title, msg) {
var title = title || 'Error';
var msg = msg || 'Error on Request';
}
为什么这个人使用 var title = title ||'错误'?我有时也会看到它没有 var 声明.
Why is this guy using var title = title || 'ERROR'? I sometimes see it without a var declaration as well.
推荐答案
这意味着 title 参数是可选的.因此,如果您调用不带参数的方法,它将使用默认值 "Error".
It means the title argument is optional. So if you call the method with no arguments it will use a default value of "Error".
这是写作的简写:
if (!title) {
title = "Error";
}
这种布尔表达式的速记技巧在 Perl 中也很常见.用表达式:
This kind of shorthand trick with boolean expressions is common in Perl too. With the expression:
a OR b
如果 a 或 b 为 true,则计算结果为 true.因此,如果 a 为真,则根本不需要检查 b.这称为短路布尔评估,因此:
it evaluates to true if either a or b is true. So if a is true you don't need to check b at all. This is called short-circuit boolean evaluation so:
var title = title || "Error";
基本上检查 title 的计算结果是否为 false.如果是,则返回"Error",否则返回title.
basically checks if title evaluates to false. If it does, it "returns" "Error", otherwise it returns title.
相关文章