本文介绍了JavaScript数组的布尔评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前几天我遇到了一个有趣的错误。我正在测试一个数组以查看它是否被评估为布尔值false,但只是直接评估它总是返回true:

I ran across an interesting bug the other day. I was testing an array to see if it evaluated to Boolean false, however just directly evaluating it always returned true:

> !![]
  true

好的,基本上我放在那里的任何数组都会是 true 无论如何,对吗?我在JavaScript控制台中运行它只是为了好玩:

Okay, so basically any array I put in there will be true regardless, right? I run this in the JavaScript console just for fun:

> [] == true
  false

这里发生了什么?

推荐答案

它与与用于将值转换为布尔值的算法。

It has to do with the The Abstract Equality Comparison Algorithm versus the algorithm used to tranform a value to a boolean.

通过查找在中,我们可以看到这一点数字 9。是唯一一个定义类型(左侧值)为对象时应该发生什么的数字。但是它指定右侧值必须是字符串或数字

By looking at the spec, we can see that the point number 9. is the only one that defines what should be happening when Type(left side value) is Object. However it's specifying that the right side value has to be either String or Number.

查看 [] == true

typeof [] 'object'所以我们没事,但 typeof true 是不是'string''number',它是'boolean',所以它回退到最后一个语句,点数 10。

typeof [] is 'object' so we are fine, but typeof true is not 'string' or 'number', it is 'boolean', so it fallback to the last statement, point number 10.

然而 !! [] 转换为 !! Boolean([]),并且因为 [] 是一个thruty值(对象是),它与写<$相同c $ c> !! true ,返回 true

However !![] translates into !!Boolean([]), and since [] is a thruty value (objects are), it's the same as writing !!true, which returns true.

这篇关于JavaScript数组的布尔评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:41