问题描述
我正在调试一些 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
.
这篇关于什么是构造 x = x ||你是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!