# 为什么（’b’+’a’+ +’a’+’a’）。toLowerCase（）’banana’的结果？

2020/09/23 21:21 · javascript ·  · 0评论

``document.write(('b' + 'a' + + 'a' + 'a').toLowerCase());``

`+'a'`解析为`NaN`（“非数字”），因为它会将字符串强制转换为数字，而`a`无法将字符解析为数字。

``document.write(+'a');``

``document.write('ba'+(+'a')+'a');``
``'b' + 'a' + + 'a' + 'a'``

``('b') + ('a') + (+'a') + ('a')``

（请参阅：运算符优先级

`(+'a')`尝试`'a'`使用一元加运算符将其转换为数字因为`'a'`不是数字，所以结果为`NaN`“ Not-A-Number”）：

``'b'  +  'a'  +  NaN  + 'a'``

``'b'  +  'a'  +  NaN  + 'a'  =>  'baNaNa'``

``'baNaNa'.toLowerCase()      =>  'banana'``
``('b' + 'a' + + 'a' + 'a').toLowerCase()``

# 步骤1

``'b' + 'a' + + 'a' + 'a'``

• `'b' + 'a'`返回ba，这是常规串联。
• `ba + + 'a'`尝试将ba连接`+ 'a'`但是，由于一元运算符`+`尝试将其操作数转换为数字，因此将返回NaN，然后将其与原始ba串联时将其转换为字符串-从而得出baNaN
• `baNaN`+'a'返回baNaNa同样，这是常规连接。

# 第二步

``````=> ( ('b') + ('a') + (++) + ('a') + ('a'))
=> ( ('b') + ('a') + (+) + ('a') + ('a')) // Here + + convert it to +operator
Which later on try to convert next character to the number.``````

``const string =  '10';``

1. 数字（字符串）；
2. +字串;

``````( ('b') + ('a') + (+'a') + ('a'))
( ('b') + ('a') + NaN + ('a'))``````

``( ('b') + ('a') + 'NaN' + ('a'))``

``( 'b' + 'a' +  + '1' + 'a' ) ``

``````const example1 = ('b' + 'a' + + 'a' + 'a').toLowerCase(); // 'banana'
const example2 = ('b' + 'a' + + '1' + 'a').toLowerCase(); // 'ba1a'
console.log(example1);
console.log(example2);``````

The expression `('b' + 'a' + + 'a' + 'a')` is solely composed of string literals and addition operators.

• String Literals "A string literal is zero or more characters enclosed in single or double quotes."
• The Addition operator ( + ) "The addition operator either performs string concatenation or numeric addition."

An implicit action taken is the call for ToNumber on a string

• ToNumber Applied to the String Type "ToNumber applied to Strings applies grammar to the input String. If the grammar cannot interpret the String as an expansion of StringNumericLiteral, then the result of ToNumber is NaN."

The interpreter has rules of how to parse the expression, by breaking it down into its components of left and right hand expressions.

Step 1: `'b' + 'a'`

## 使用+将在JavaScript中将任何值转换为Number！

W3SchoolsMozilla开发人员网络上了解有关NaN的更多信息

``````console.log(('b' + 'a' + + 'a' + 'a').toLowerCase());
console.log(('b' + 'a' + + 'a' + 'a'));
console.log(('b' + 'a' + 'a' + 'a').toLowerCase());``````