2013-11-22 35 views
2

console.log()對於數字的行爲有所不同。在控制檯中寫入數字時出現奇怪的行爲

以下發現很有趣。任何解釋?

console.log(1) - 1

console.log(01) - 1

console.log(12) - 12

console.log(012) - 10

console.log(0123) - 83

console.log(123) - 123

編輯

MDN documentation:

Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). 

Decimal integer literal consists of a sequence of digits without a leading 0 (zero). 
Leading 0 (zero) on an integer literal indicates it is in octal. Octal integers can include only the digits 0-7. 
Leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F. 
Octal integer literals are deprecated and have been removed from the ECMA-262, Edition 3 standard (in strict mode). JavaScript 1.5 still supports them for backward compatibility. 
+1

'console.log(012); // 10'當調試這樣奇怪的東西時,減少代碼以消除可能不相關的方法。 –

+0

@KevinB - 你是對的。應該做到這一點。認爲該功能表現怪異。不是。 – Krishna

回答

3

發現這個這有什麼好做的jQuery;它只是ECMAScript的一個特性/怪癖(因此也是JavaScript)。以0開頭的數字文字以八進制解釋,而不是十進制(除非在嚴格模式下,在這種情況下它會產生語法錯誤)。

您可以通過觀察012 === 10=== 83進行驗證。

+0

謝謝。我計算它和一切都匹配,但不知道爲什麼八進制。 – Krishna

+0

您可以通過使用'號「修剪」前導零(「0123」)' –

+0

@NoahHeldman在這種情況下,可以更好地使用_parseInt_或_parseFloat_比_NUMBER_。 –

相關問題