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

查看:27
本文介绍了构造 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

如果 abtrue,则计算结果为 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 || 是什么?你的意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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