“x = x ||”的目的是什么? 0&QUOT ;? [英] What is the purpose of "x = x || 0"?

查看:84
本文介绍了“x = x ||”的目的是什么? 0&QUOT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看我在网上找到的一些代码时,我发现了这个特殊的代码行(Javascript):

In looking through some code I found online, I found this peculiar line of code (Javascript):

function values(b) {
    this.b = b || 0;
}

我根本无法弄清楚<$ c $的目的是什么C> || 0 。如果我没弄错,因为 || 返回一个布尔值,这个值 b 将始终是布尔值相当于参数。如果 b 传递为true(即 1 true ),然后 b 应为真;否则,使用其中一个 false 值(即 NaN 0 ),这应该是假的。然后我解释如下:

I simply can't figure out what the purpose of the ||0. If I'm not mistaken, since || returns a boolean, this value, b will always be whatever the boolean equivalent of the parameter is. If b is passed as true (ie 1 or true), then b should be true; otherwise, using one of the false values (ie. NaN, 0), this should be false. I then interpret this as the following:

b true

this.b = true || false; // will evaluate to true

b false

this.b = false || false; // will evaluate to false

我只是看不到添加<$ c $所获得的价值C> || 0 。有人可以向我解释一下吗?

I just don't see the value gained by adding ||0. Could someone please explain this to me?

推荐答案

|| 变量赋值是指定默认值的常用方法。这是因为JavaScript的虚假值。在JavaScript中,未定义 null ,空字符串和 0 所有在布尔上下文中评估为 false

|| in a variable assignment is a common way to specify a default value. This is because of JavaScript's falsy values. In JavaScript, undefined, null, empty string and 0 all evaluate to false in a boolean context.

例如:

var blah = undefined;
if (blah) {
    console.log('got it!');
}
else {
    console.log('not true!');  // this one outputs
}

使用 || 是一种说法如果已定义,则使用此。

Using || in an assignment is a way of saying "if defined, otherwise use this".

对于此代码,

function values(b) {
    this.b = b || 0;
}

我们可以使用真值表:

b          this.b
------------------
5          5
10         10
0          0
undefined  0
null       0
''         0

真正感兴趣的值是 undefined null 。所以我们真正想要的是:

The values really of interest are undefined and null. So what we really want is:

if (b !== undefined && b !== null) {
    this.b = b;
}
else {
    this.b = 0;
}

this.b = b || 0 写得更短。

这篇关于“x = x ||”的目的是什么? 0&QUOT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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