rac*_*101 70 javascript arrays conditional object
我在代码中遇到了很多错误,因为我期待这个表达式:
Boolean([]); 评估为假.
但事实并非如此,因为它评估为真.
因此,可能返回的函数[]如下:
// Where myCollection possibly returned [ obj1, obj2, obj3] or []
if(myCollection)
{
// ...
}else
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
没有做到预期的事情.
我错误地假设[]一个空数组?
此外,这种行为在所有浏览器中是否一致?或者那里有任何陷阱吗?顺便说一句,我在Goolgle Chrome中观察到了这种行为.
Bar*_*mar 82
来自http://www.sitepoint.com/javascript-truthy-falsy/
以下值始终是假的:
所有其他值都是真实的,包括"0"(引号中为零),"false"(引号中为false),空函数,空数组和空对象.
Dev*_*One 17
您应该检查该.length数组,看它是否包含任何元素.
if (myCollection) // always true
if (myCollection.length) // always true when array has elements
if (myCollection.length === 0) // same as is_empty(myCollection)
Run Code Online (Sandbox Code Playgroud)
小智 16
[]==false // returns true
Run Code Online (Sandbox Code Playgroud)
由于ECMA 规范 #Section 11.9.3中提到的抽象相等算法,此结果为 true
如果您运行上面提到的算法。
在第一次迭代中,满足的条件是,
Step 7: If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
因此上述条件转化为 ->[] == 0
现在在第二次迭代中,条件满足[] == 0:
Step 9: If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.
[] 是一个对象,从此以后,在转换为原始类型时,它会转换为空字符串''
因此,上述条件转化为 ->'' == 0
在第三次迭代中,满足的条件是:
Step 5: If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
众所周知,空字符串''是一个falsy值,因此将空字符串转换为数字将返回一个值0。
从此以后,我们的情况,将转变为 ->0 == 0
在第四次迭代中,满足第一个条件,其中类型相等并且数量相等。
从此以后,最终的值[] == false归约为0 == 0true。
希望这能回答您的问题。否则,您也可以参考此YouTube 视频
当
[]等于 时false,它的计算结果为true。
是的,这听起来很糟糕,或者至少有点令人困惑。看看这个:
const arr = [];
if (arr) console.log("[] is truethy");
if (arr == false) console.log("however, [] == false");Run Code Online (Sandbox Code Playgroud)
在实践中,如果你想检查某个东西是否为空,那么检查length. (?.运营商确保也null包括在内。)
const arr = []; // or null;
if (!arr?.length) console.log("empty or null")Run Code Online (Sandbox Code Playgroud)