你能在javascript中解释对象和数组算法吗?

时间:2015-02-20 23:40:49

标签: javascript

任何人都可以解释为什么这些操作会产生这些结果:

(据我所知,第一个与基于数组的字符串有关,但'基于'的含义是什么意思,内部如何工作)

[] + [] = ""

[] - []= 0

[] + {} = "[object Object]"

[] - {} = NaN

{} + {} = NaN

{} - {} = NaN

{} + 1 = 1

1 个答案:

答案 0 :(得分:5)

当使用+运算符时,javascript将尝试将首先添加的元素转换为字符串,然后转换为int。当您将空数组转换为字符串时,您会"" "" + "" = ""

[] + [] = ""  // equates to "" + "" = ""

使用-运算符时,javascript会尝试将元素转换为整数。转换为整数的空数组将生成0 0 - 0 = 0

[] - []= 0 // equates to 0 - 0 = 0

同样的事情是,空数组正在转换为""并且对象正在转换为"[object Object]",因为与空字符串串联,结果为"" + "[object Object]" = "[object Object]"

[] + {} = "[object Object]" // equates to "" + "[object Object]" = "[object Object]"

{}无法转换为int,因此转换为undefined0 - undefined = NaN

[] - {} = NaN // equates to 0 - undefined = NaN

当表达式以空对象文字开头时,javaScript将第一个{}解释为空代码块并忽略它,因此将以下表达式计算为+ {} <{1}} {/ 1}}

NaN