This question already has answers here:
Validate decimal numbers in JavaScript - IsNumeric()
(49个答案)
2年前关闭。
我正在加载JSON文件,并使用for循环将值读入数组
我担心有时JSON文件可能会损坏,即Im读入的值可能会变成ASCII字母,即1t3,该值应为123
是否有一个测试用例,您可以说value [a]不等于数字,然后将其设置为“”或空白
谢谢,
本
MDN Web文档在Regular Expressions上有一个超级有用的页面。
(49个答案)
2年前关闭。
我正在加载JSON文件,并使用for循环将值读入数组
我担心有时JSON文件可能会损坏,即Im读入的值可能会变成ASCII字母,即1t3,该值应为123
是否有一个测试用例,您可以说value [a]不等于数字,然后将其设置为“”或空白
谢谢,
本
最佳答案
您可以使用parseInt()函数并检查它是否返回整数或NaN。您可以在W3schools或MDN Web Docs上查看有关它的信息。
但是,我认为使用正则表达式会更好。如果您阅读parseInt()的w3schools示例,它们将显示“ 0x10”为16。
对于正则表达式,请尝试以下操作:
function isNumber(n) {
// Added checking for period (in the case of floats)
var validFloat = function () {
if (n.match(/[\.][0-9]/) === null || n.match(/[^0-9]/).length !== 1) {
return false;
} return true;
};
return n.match(/[^0-9]/) === null ? true : validFloat();
}
// Example Tests for Code Snippet
console.log(isNumber("993"));
console.log(isNumber("0t1"));
console.log(isNumber("02-0"));
console.log(isNumber("0291"));
console.log(isNumber("0x16"));
console.log(isNumber("8.97"));
MDN Web文档在Regular Expressions上有一个超级有用的页面。