为什么 javascript 中的 parseInt() 将“1abc”转换为 1?
why parseInt() in javascript converting "1abc" to 1?
我正在尝试了解 parseInt() 如何在 javascript 中工作,我的场景是
var x = parseInt("123");
console.log(x); // outputs 123
var x = parseInt("1abc");
console.log(x); // outputs 1
var x = parseInt("abc");
console.log(x); // outputs NaN
根据我的观察,当字符串以数字开头时,parseInt() 将字符串转换为整数(不是真正的字符串整数,如“12sv”)。
但实际上它应该 return NaN。
发件人:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
"If the first character cannot be converted to a number, parseInt returns NaN."
来自 Mozilla's docs:"If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point."
所以它会解析到第一个无效字符,丢弃字符串的其余部分,然后 return 它设法解析到那时的 int。如果没有有效字符,它将 return NaN。
parseInt()
->它只是将提供的值解析为其等效的基数转换,如果没有指定基数,它将转换为十进制等效值。
出于强制目的,我们应该避免使用 parseInt,我们可以使用 Number()
函数代替。
我正在尝试了解 parseInt() 如何在 javascript 中工作,我的场景是
var x = parseInt("123");
console.log(x); // outputs 123
var x = parseInt("1abc");
console.log(x); // outputs 1
var x = parseInt("abc");
console.log(x); // outputs NaN
根据我的观察,当字符串以数字开头时,parseInt() 将字符串转换为整数(不是真正的字符串整数,如“12sv”)。
但实际上它应该 return NaN。
发件人:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
"If the first character cannot be converted to a number, parseInt returns NaN."
来自 Mozilla's docs:"If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point."
所以它会解析到第一个无效字符,丢弃字符串的其余部分,然后 return 它设法解析到那时的 int。如果没有有效字符,它将 return NaN。
parseInt()
->它只是将提供的值解析为其等效的基数转换,如果没有指定基数,它将转换为十进制等效值。
出于强制目的,我们应该避免使用 parseInt,我们可以使用 Number()
函数代替。