简体   繁体   English

Javascript编译器行为 - 对于空数组和零数组的数组加倍是.. ONE

[英]Javascript Compiler behavior - double plus for array of empty array and array of zero is.. ONE

My question may be already answered, but I could not find it not in Search Engines google or bing doesn't like '+' (plus) sign in search request. 我的问题可能已经回答了,但我找不到搜索引擎中的谷歌或者bing不喜欢'+'(加号)登录搜索请求。

Anyway, why this is zero 无论如何,为什么这是零

+[[]][0] // = 0

and this is one 这是一个

++[[]][0] // = 1

UPD: Michael Berkowski have a good answer, but I steal don't understand one thing UPD: Michael Berkowski有一个很好的答案,但我偷了不明白一件事

if [[]][0] evaluates to an empty array, then why ++[] is ReferenceError: Invalid left-hand side expression in prefix operation if [[]][0]计算为空数组,那么为什么++[]ReferenceError: Invalid left-hand side expression in prefix operation

UPD2: now I get it.. it seems I was trying to type ++0 in console and getting an Error, but I should be using var a = 0; UPD2:现在我明白了......似乎我试图在控制台中键入++ 0并获得错误,但我应该使用var a = 0; ++a ++一个

This is best explored by breaking down the way its components evaluate. 通过分解其组件评估的方式可以最好地探索这一点。

[[]][0] alone evaluates to the empty array [] . 单独[[]][0]计算为空数组[] By adding + in front, you cast its string representation to an integer 0 (like saying +4 or -3 ) via a unary positive operator. 通过在前面添加+ ,您可以通过一元正算子将其字符串表示形式转换为整数0(如说+4-3 )。 +0 is just 0 . +0只是0

++ as a numeric operator, also casts the empty string to an integer 0 , but applies its operation (the prefix increment) resulting 1 . ++作为数字运算符,也将空字符串转换为整数0 ,但应用其操作(前缀增量)得到1

[[]][0]
// [] empty array
[[]][0].toString()
// ""

// Unary + casts the empty string to an integer
+("")
// 0

// Prefix increment on an empty string results in 1 (increments the 0)
var emptyString = "";
++emptyString;
// 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM