简体   繁体   English

这段代码意味着什么([1,2,3] || 0)[0]

[英]What this code means ([1, 2, 3] || 0)[0]

Closure(Script) implementation in JavaScript called "wisp" has this snippet: JavaScript中的闭包(脚本)实现称为“wisp”有这个片段:

(get [1 2 3] 1) ; => ([1, 2, 3] || 0)[0]

which means that the wisp code compiles to this in JavaScript: 这意味着wisp代码在JavaScript中编译为:

([1, 2, 3] || 0)[0]

But why is || 0 但为什么是|| 0 || 0 part there? || 0部分吗?

My guess is that instead of writing a literal array, you can send it a variable: 我的猜测是,你可以发送一个变量,而不是写一个文字数组:

(get x 1) ;

So the || 0 所以|| 0 || 0 is used in case x is null or undefined . 如果xnullundefined则使用|| 0

In JavaScript, || 在JavaScript中, || does not return a boolean, it returns the 1st value if it's "truthy" and the 2nd if the 1st is "falsy". 不返回布尔值,如果它是“truthy”则返回第1个值,如果第1个值是“falsy”则返回第2个值。

0[0] returns undefined just like [][0] does. 0[0]返回undefined就像[][0]一样。 0 is one less character than [] , so that's probably why they did || 0 0[]少一个字符,所以这可能是他们做|| 0 || 0 instead of || [] || 0而不是|| [] || [] . || []

Normally it would be used to specify a default value if the first part is null/undefined/false. 通常,如果第一部分为null / undefined / false,它将用于指定默认值。

For example, consider the following code: 例如,请考虑以下代码:

var a = 1;
var b;

var x = a || 0;//if a is true use a, otherwise use 0
var y = b || 0;//if b is true use b, otherwise use 0

The value of x will be 1 , because 1 is a truthy value and therefore becomes the value that is used. x的值将为1 ,因为1是真值,因此成为使用的值。 whereas y will be 0 because the value of b is undefined (a falsey value) so the 0 is used instead. y将为0因为b的值未定义(假值),因此使用0代替。

In your example however it is pointless, as [1, 2, 3] will always be true. 在你的例子中,它是毫无意义的,因为[1, 2, 3]将永远是真的。 But if you was using a variable then is would be possible for the variable to not be assigned, so the default value would then apply. 但是,如果您使用的是变量,则可能无法分配变量,因此将应用默认值。

Here is an example that shows how different types would apply 这是一个示例 ,显示了不同类型的应用方式

Here is more information on Truthy and Falsey vaues 以下是有关Truthy和Falsey vaues的更多信息

I don't believe that the || 0 我不相信|| 0 || 0 does anything. || 0做任何事情。 The || || operator checks for a null, undefined etc, and if found will return the right hand side of the expression. 运算符检查null,undefined等,如果找到则返回表达式的右侧。

In this example [1, 2, 3] is never null so 0 will never be returned. 在此示例中, [1, 2, 3]永远不为null,因此永远不会返回0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM