javascript - 如何使用javascript检查var是字符串还是数字

标签 javascript typeof

我有一个变量 var number="1234",虽然这个数字是一个数值,但它在 "" 之间,所以当我使用 检查它时typeofNaN 我得到它作为一个字符串。

function test()
{
    var number="1234"

if(typeof(number)=="string")
{
    alert("string");
}
if(typeof(number)=="number")
{
    alert("number");
}

}

我总是得到alert("string"),你能告诉我如何检查这是否是一个数字吗?

最佳答案

据我了解你的问题是要求测试 检测一个字符串是否表示一个数值。

快速测试应该是

function test() {
   var number="1234"
   return (number==Number(number))?"number":"string"
}

作为数字,如果调用时没有使用 new 关键字,则将字符串转换为数字。 如果变量内容未被修改(== 会将数值转换回字符串) 你正在处理一个数字。否则它是一个字符串。

function isNumeric(value) {
   return (value==Number(value))?"number":"string"
}

/* tests evaluating true */
console.log(isNumeric("1234"));  //integer
console.log(isNumeric("1.234")); // float
console.log(isNumeric("12.34e+1")); // scientific notation
console.log(isNumeric(12));     // Integer
console.log(isNumeric(12.7));   // Float
console.log(isNumeric("0x12")); // hex number

/* tests evaluating false */
console.log(isNumeric("1234e"));
console.log(isNumeric("1,234"));
console.log(isNumeric("12.34b+1"));
console.log(isNumeric("x"));

关于javascript - 如何使用javascript检查var是字符串还是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6799877/

相关文章:

dojo - 带滚动的 dijit.TitlePane?

javascript - 将 Firefox 窗口置于全屏模式

javascript - 在html head中解析外部资源

javascript - 如何在 JavaScript 中从 IANA 时区代码获取时区偏移量?

reactjs - 模块解析失败 : Unexpected token. react-native/index.js "typeof"operator

c - 如何在 C 中实现 typeof 运算符

javascript - 嵌入的 js 文件不适用于 jQuery .load() 内容

c++ - c++11 中的关键字 typeof

javascript - JavaScript 中的 new String ("x") 有什么意义?

javascript - 在 Javascript 中仅使用 typeof 运算符检查类型是否错误?