我正在加载一个JSON文件,使用for循环
将值读入数组我担心有时JSON文件可能会损坏,即我读入的值可能会变为ASCII字母,即1t3,其中值应为123
是否有测试用例可以说明值[a]是否等于数字然后将其设置为“”或空白
谢谢, 本
答案 0 :(得分:1)
您可以使用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网络文档在Regular Expressions上有一个非常实用的页面。