Javascript数组等于零但不是自身 [英] Javascript array equal to zero but not itself

查看:141
本文介绍了Javascript数组等于零但不是自身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用JavaScript中的数组,但无法弄清楚为什么会发生这种情况:

I've been playing around with arrays in JavaScript and cannot figure out why this happens:

console.log(0 == 0)
//true

console.log([] == 0)
//true

console.log(0 == [])
//true

console.log([] == [])
//false

console.log([] == ![])
// true

空数组等于左右都为零,但为什么它不等于它自己?

The empty array is equal enough to zero both left and right, but why isn't it equal to itself?

我意识到比较两个对象不会导致 true ,但为什么他们被强制转换为 0 (或者是假的,不应该是这种情况)如果将它们与 0 进行比较,如果将它们与另一个数组进行比较,则将其作为对象进行比较?

I realise that comparing two objects would not result true, but why are they coerced to 0 (or falsy, which shouldn't be the case) if you compare them to 0, while threated as an object if you compare them to the other array?

推荐答案

console.log(0 == [])
//true 

您正在尝试将对象与整数进行比较,因此您的对象被隐式类型化为等效的整数值0

You are trying to compare object with an integer, so your object is implicitly typecasted to equivalent integer value that is 0

console.log([] == [])
//false 

因为两个对象永远不会相等

as two objects are never equal

这篇关于Javascript数组等于零但不是自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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