将字符串值解析为 JavaScript 中的十六进制

Parsing string value to hex in JavaScript

这很奇怪,不是吗?如果我只记得0-9,A、B、C、D、E、F字母代表一个十六进制值。为什么 ABCDEFGHAIJ 有十六进制表示?

epascarello in the comments, here is the relevant part of the MDN documentation 所述,以解释此行为:

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. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

因此,parseInt("abcdefghij", 16) 将实际解析 "abcdef" 并停在那里。因此结果:

0xABCDEF = 11259375

了解这一点后,您可能希望使用一个自定义函数,该函数将在使用非十六进制字符串调用时代替 return NaN

function parseTrueHexa(str) {
  return str.match(/^ *[a-f0-9]+ *$/i) ? parseInt(str, 16) : NaN;
}

console.log("parseInt() says:");
console.log(parseInt("aBcD", 16));
console.log(parseInt("abcdz", 16));

console.log("parseTrueHexa() says:");
console.log(parseTrueHexa("aBcD"));
console.log(parseTrueHexa("abcdz"));