如果([] == false)为true,为什么([] || true)导致[]? [英] If ([] == false) is true, why does ([] || true) result in []?

查看:127
本文介绍了如果([] == false)为true,为什么([] || true)导致[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是做一些测试,我发现这个奇怪:

Was just doing some testing and I find this odd:

[] == false

这是有道理的,因为double等于只比较内容而不是类型,并尝试进行类型强制。但是如果它的比较内容和返回true,那意味着[]是假的(如果你 [] == true 你也得到false),这意味着:

Gives true, this makes sense because double equal only compares contents and not type and tries to do type-coercion. But if its comparing contents and returns true, that means [ ] is falsey (if you did [] == true you get false too), which means:

[] || false

应该给出假,但它给出[],使其真实吗?为什么?

Should give false, but it gives [ ], making it truthy? Why?

另一个例子:

"\n  " == 0

给出true,但\\\
|| false
给予\\\

Gives true, but "\n " || false gives "\n "? Is there an explanation for this or its just an oddity.

当我在C中尝试这个时,我们得到:

When I tried this in C, we get:

int x = "\n " == 0;
printf("%d\n", x);

int y = "\n " || 0;
printf("%d\n", y);

输出:

0
1

这是有意义的, ,行为不同。

This makes sense, but given C's influence on Javascript, the behaviour is different.

推荐答案

类型转换与假的和真实的值无关。

Type conversion is not related to falsy and truthy values.

什么是真实,什么是虚假是由 在规范和 [] 中定义的ToBoolean 函数确实是真实的。

What is truthy and what is falsy is defined by the ToBoolean function defined in the specs and [] is indeed truthy.

另一方面,由于 [] == false 会返回 true //es5.github.io/#x11.9.3rel =nofollow>类型转换

On the other hand, [] == false returns true because of the type conversion that happens during the evaluation of the expression.

类型转换规则表示 x == y


)是布尔值,返回比较结果x == ToNumber(y)。

If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

ToNumber 的结果为0表示false,所以我们留下评估 [] == 0 。根据相同的规则


如果Type(x)是Object,类型(y)是String或Number,比较ToPrimitive(x)== y。

If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.

ToPrimitive 会生成一个空字符串。现在我们有== 0 。返回类型转换规则

ToPrimitive results in an empty string. Now we have "" == 0. Back to our type conversion rules


如果Type(x)是String,Type(y)是Number,
返回结果比较ToNumber(x)== y。

If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.

ToNumber 评估是 0 == 0 ,即 true

这篇关于如果([] == false)为true,为什么([] || true)导致[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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