Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

javascript - x = x ||的构造是什么 你的意思是?(What does the construct x = x || y mean?)

I am debugging some JavaScript, and can't explain what this ||(我正在调试一些JavaScript,无法解释||)

does?(有吗)
function (title, msg) {
  var title = title || 'Error';
  var msg   = msg || 'Error on Request';
}

Can someone give me an hint, why this guy is using var title = title || 'ERROR'(有人可以给我一个提示,为什么这个人使用var title = title || 'ERROR')

var title = title || 'ERROR' ?(var title = title || 'ERROR' ?) I sometimes see it without a var declaration as well.(我有时也看到它没有var声明。)   ask by opHASnoNAME translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It means the title argument is optional.(这意味着title参数是可选的。)

So if you call the method with no arguments it will use a default value of "Error" .(因此,如果不带任何参数调用该方法,它将使用默认值"Error" 。)

It's shorthand for writing:(它是写作的简写:)

if (!title) {
  title = "Error";
}

This kind of shorthand trick with boolean expressions is common in Perl too.(这种带有布尔表达式的速记技巧在Perl中也很常见。)

With the expression:(带有表达式:)
a OR b

it evaluates to true if either a or b is true .(它的计算结果为true如果任abtrue 。)

So if a is true you don't need to check b at all.(因此,如果a为true,则根本不需要检查b 。) This is called short-circuit boolean evaluation so:(这称为短路布尔评估,因此:)
var title = title || "Error";

basically checks if title evaluates to false .(基本上检查title评估结果是否为false 。)

If it does, it "returns" "Error" , otherwise it returns title .(如果是这样,它将“返回” "Error" ,否则返回title 。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...