6

JavaScript中神奇的+

 3 years ago
source link: https://www.lujun9972.win/blog/2019/08/14/javascript%E4%B8%AD%E7%A5%9E%E5%A5%87%E7%9A%84+/index.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript中神奇的+

今天又看到一个JavaScript的骚操作:

('b' + 'a' + + 'a' + 'a').toLowerCase()
// =>"banana"

理解这一发的关键在于理解 + + 'a' 是什么意思。

我们一看到 + 可能下意识就认为是做 加法, 却很容易忽略它也可能是 正号. 所以这里两个 加号 的意义其实是不同的,第一个 加号 表示 加法,而第二个 加号 表示 正号. 而 'a' 并不是数字,因此 + 'a' 的值会是 NaN,因此上面的语句就变成了

('b' + 'a' + NaN + 'a').toLowerCase()

而再根据加法操作的规则:

  1. 如果两个操作数都是字符串,则将第二个操作数与第一个操作数拼接起来
  2. 如果有一操作数为对象,数字或者布尔值,则调用它们的toString()方法取得相应的字符串的值,再进行字符串拼接

因此上面的语句就变成了

('b' + 'a' + NaN.toString() + 'a').toLowerCase()

=>

('b' + 'a' + 'NaN' + 'a').toLowerCase()

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK