In JavaScript, all objects are truthy (as per the spec). In the DOM, there’s one exception to this rule. What is it? #jsquiz #fronttrends
有人知道答案吗?
最佳答案
免责声明: I’m the guy who tweeted that :)这是我会在 Front-Trends 中提出和回答的问题。讲话。我在上台前 5 分钟写了那条推文。
由于 Twitter 上有 140 个字符的限制,这个问题有点模棱两可。我问的真正问题如下。
ECMAScript 规范 defines ToBoolean()
as follows :
如您所见,所有非原始对象(即所有不是 bool 值、数字、字符串、undefined
或 null
的对象)都是按照规范真实。然而,在 DOM 中,有一个异常(exception)——DOM 对象是假的。你知道那是哪一个吗?
答案是 document.all
。 The HTML spec说:
The
all
attribute must return anHTMLAllCollection
rooted at theDocument
node, whose filter matches all elements.The object returned for all has several unusual behaviors:
The user agent must act as if the
ToBoolean()
operator in JavaScript converts the object returned forall
to thefalse
value.The user agent must act as if, for the purposes of the
==
and!=
operators in JavaScript, the object returned forall
is equal to theundefined
value.The user agent must act such that the
typeof
operator in JavaScript returns the string'undefined'
when applied to the object returned forall
.These requirements are a willful violation of the JavaScript specification current at the time of writing (ECMAScript edition 5). The JavaScript specification requires that the
ToBoolean()
operator convert all objects to thetrue
value, and does not have provisions for objects acting as if they wereundefined
for the purposes of certain operators. This violation is motivated by a desire for compatibility with two classes of legacy content: one that uses the presence ofdocument.all
as a way to detect legacy user agents, and one that only supports those legacy user agents and uses thedocument.all
object without testing for its presence first.
因此,document.all
是此 ECMAScript 规则的唯一官方异常(exception)。 (在 Opera 中,document.attachEvent
等也是假的,但在任何地方都没有指定。)
关于javascript - 根据规范,JavaScript 中的所有对象都是真实的,但在 DOM 中,一个非原始对象不是。哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10348995/