Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

javascript - 为什么('b'+'a'+ +'a'+'a')。toLowerCase()'banana'的结果?(Why is the result of ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana'?)

I was practicing some JavaScript when one of my friends came across this JavaScript code:

(当我的一个朋友遇到以下JavaScript代码时,我正在练习一些JavaScript:)

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

The above code answers "banana" !

(上面的代码回答"banana" !)

Can anyone explain why?

(谁能解释为什么?)

  ask by HV Sharma translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

+'a' resolves to NaN ("Not a Number") because it coerces a string to a number, while the character a cannot be parsed as a number.

(+'a'解析为NaN (“非数字”),因为它将字符串强制为数字,而字符a不能解析为数字。)

 document.write(+'a'); 
To lowercase it becomes banana .

(小写变成banana 。)

Adding NaN to "ba" turns NaN into the string "NaN" due to type conversion, gives baNaN .

(将NaN添加到"ba"会由于类型转换而将NaN变成字符串"NaN" ,得到baNaN 。)

And then there is an a behind, giving baNaNa .

(然后是a后面是baNaNa 。)

The space between + + is to make the first one string concatenation and the second one a unary plus (ie "positive") operator.

(+ +之间的空格是使第一个字符串串联,而第二个字符串成为一元加号(即“正”)运算符。)

You have the same result if you use 'ba'+(+'a')+'a' , resolved as 'ba'+NaN+'a' , which is equivalent to 'ba'+'NaN'+'a' due to type juggling.

(如果使用'ba'+(+'a')+'a' ,则得到相同的结果,解析为'ba'+NaN+'a' ,等效于'ba'+'NaN'+'a'打杂耍。)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...