Zhi*_*har 2 javascript string jquery parsing converter
提示是否有可能将字符串转换为数字,以便只有整数以外的任何其他变体都会产生错误。
func('17') = 17;
func('17.25') = NaN
func(' 17') = NaN
func('17test') = NaN
func('') = NaN
func('1e2') = NaN
func('0x12') = NaN
ParseInt无法正常工作,因为它无法正常工作。
ParseInt('17') = 17;
ParseInt('17.25') = 17 // incorrect
ParseInt(' 17') = NaN
ParseInt('17test') = 17 // incorrect
ParseInt('') = NaN
ParseInt('1e2') = 1 // incorrect
最重要的是:该功能可在IE,Chrome和其他浏览器中使用!!!
您可以使用正则表达式和三元运算符来拒绝所有包含非数字的字符串:
function intOrNaN (x) {
  return /^\d+$/.test(x) ? +x : NaN
}
console.log([
  '17', //=> 17
  '17.25', //=> NaN
  ' 17', //=> NaN
  '17test', //=> NaN
  '', //=> NaN
  '1e2', //=> NaN
  '0x12' //=> NaN
].map(intOrNaN))