空数组似乎同时为真和假 [英] Empty arrays seem to equal true and false at the same time

查看:125
本文介绍了空数组似乎同时为真和假的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

空数组为true但它们也等于false。

Empty arrays are true but they're also equal to false.

var arr = [];
console.log('Array:', arr);
if (arr) console.log("It's true!");
if (arr == false) console.log("It's false!");
if (arr && arr == false) console.log("...what??");

我想这是由于等式运算符操作的隐式转换。

I guess this is due to the implicit conversion operated by the equality operator.

任何人都可以解释会发生什么在幕后?

Can anyone explain what's going on behind the scenes?

推荐答案

你在这里测试不同的东西。

You're testing different things here.

if(arr)在对象上调用(Array是JS中的Object实例)将检查对象是否是present,并返回true / false。

if (arr) called on object (Array is instance of Object in JS) will check if the object is present, and returns true/false.

当你调用 if(arr == false)时,你要比较的值 object和原始 false 值。在内部,调用 arr.toString(),它返回一个空字符串

When you call if (arr == false) you compare values of this object and the primitive false value. Internally, arr.toString() is called, which returns an empty string "".

这是因为在Array上调用的 toString 返回 Array.join(),空字符串是JavaScript中的一个虚假值。

This is because toString called on Array returns Array.join(), and empty string is one of falsy values in JavaScript.

这篇关于空数组似乎同时为真和假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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