构造x = x ||是什么你的意思是? [英] What does the construct x = x || y mean?

查看:171
本文介绍了构造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 声明的情况下看到它。

Can someone give me an hint, why this guy is using var title = title || 'ERROR'? I sometimes see it without a var declaration as well.

推荐答案

它表示 title 参数是可选的。因此,如果您调用没有参数的方法,它将使用默认值错误

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 ,则评估为 true b 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 是否计算为。如果是,则返回错误,否则返回 title

basically checks if title evaluates to false. If it does, it "returns" "Error", otherwise it returns title.

这篇关于构造x = x ||是什么你的意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆