空数组在比较时返回 false 但当它单独返回 true 时......为什么这样

Empty array returning false when compare but when it is alone returning true...why like this

if([]==true) //evalutes as false

//when i check empty array with true, if evaluating [] as false so it if condition return false

if([]) //evalutes as true

//when i check empty array alone, if evaluating [] as true so it if condition return true

为什么会这样评价?

谢谢

基于 abstract equality comparison algorithm 您的第一个代码将按如下方式评估,

第 1 步:ToNumber([]) == true

第 2 步:ToPrimitive([]) == true

(ToNumber() 将在传递的参数为 object 时调用 ToPrimitve())

第 3 步:"" == true

第 4 步:0 == true

第 5 步:false == true

第 6 步:false

在你的第二种情况下,[] 是一个真值,所以 if([]) 将始终被评估为真,这里 [] 不会被转换为原始值。当您使用 == 运算符时,抽象相等比较算法开始发挥作用。

另一个更好的例子是,

var x = [] || "hello";
console.log(x); // [] 

由于 [] 是一个真值,x 将设置为 [] 而不是 "hello"

当您仅使用变量作为条件(没有比较运算符)时,Javascript 将使用 Boolean() 函数将其转换为 Boolean

http://www.w3schools.com/js/js_booleans.asp

在你的例子中,Boolean([]) = true 所以它返回为真。