2017-10-18 89 views
1

~(function() {}).toString();是絕對有效的JavaScript語法,我看到它返回-1。我知道~不是運營商。例如~5 = ~0101這意味着基數2中的1010和十進制中的10爲什麼〜運算符在Javascript中爲函數返回-1?

console.log(~(function() {}).toString());

但什麼是在這種情況下如何解釋呢?

也許~NaN返回-1

+0

說明:https://www.joezimjs.com/javascript/great-mystery-of-the-tilde/ –

+1

這個,如果你同'NaN'會嘗試這樣做,就像'NaN'一樣,它會得到相同的結果。 – Krusader

回答

2

作爲每spec

設OLDVALUE是ToInt32(的GetValue(表達式))。

Number((function() {}).toString();) - >Number("function() {}") - >NaN

再次按spec

如果數是NaN,0,-0,+∞,或-∞,返回0。

所以~NaN~0這是-1

2

this blog: The Great Mystery of the Tilde(~)摘自:

波浪號是一個操作符做一些事情,你通常認爲不會有任何目的。它是一個一元運算符,它的右邊表達式對其執行這個小算法(其中N是代字號右邊的表達式):-(N+1)。見下面的一些樣品。

console.log(~-2); // 1 
console.log(~-1); // 0 
console.log(~0); // -1 
console.log(~1); // -2 
console.log(~2); // -3 
相關問題