为什么JS中的空数组加false会返回字符串? [英] Why does an empty array plus false in JS return a string?

查看:39
本文介绍了为什么JS中的空数组加false会返回字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么一个空数组加false会返回字符串"false"?

Why does an empty array plus false return the string "false"?

> [] + false

> "false"

一个空数组是假的,对吧?

An empty array is false, right?

然后,假+假=假?不?

Then false + false = false? No?

推荐答案

简短答案:因为

Short answer: because the spec says so.

更长的答案:当 + 运算符的左操作数不是字符串或数字时,该操作数将根据其首选"原始类型(定义为规格).数组的首选"类型是字符串,而 [].toString()是空字符串.

Longer answer: When the left operand of the + operator is not a string or a number, the operand will be converted to either one of those depending on their "preferred" primitive type (defined in the spec). The array's "preferred" type is a string and [].toString() is an empty string.

然后,仍然按照规范,因为左操作数是一个字符串(在上一次转换之后),所以右操作数将被转换为字符串,并且 + 操作的结果为两个字符串的串联.

Then, still according to the spec, because the left operand is a string (following the previous conversion), the right operand will be converted to a string and the result of the + operation will be the concatenation of both strings.

换句话说, [] + false 等效于 [].toString()+ false.toString()(或" +"false"),并生成字符串" false".

In other words, [] + false is equivalent to [].toString() + false.toString() (or "" + "false") and results in the string "false".

由此产生的其他有趣结果:

Other interesting results as a consequence of this:

[1,2,3] + false // "1,2,3false"
[1,[2]] + false // "1,2false"
[] + {} // "[object Object]"

这篇关于为什么JS中的空数组加false会返回字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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