我正在通过使用document.getElementById.innerHTML获取HTML元素的值,然后将该值传递给返回该值类型的函数。然后,我使用一个if / else if块将值的类型输出到控制台。我的问题是typeof方法始终返回字符串类型。如果我不使用document.getElementById并直接声明该变量,则typeof返回正确的类型。谢谢你的帮助!

JS小提琴在这里:http://jsfiddle.net/sY7uW/

// get innerhtml of div
var LowTemperature = document.getElementById('LowTemperature').innerHTML;

// check type from function return
if(check_type(LowTemperature) === 'number') {
    console.log(LowTemperature + " is a number");
}
else if(check_type(LowTemperature) === 'string') {
    console.log(LowTemperature + " is a string");
}

// return var type
function check_type(value) {
    return typeof value;
}

最佳答案

您可以尝试将值解析为整数,然后将其与原始值进行比较:

if(parseInt(LowTemperature) == LowTemperature) alert("LowTemperature is an integer");

10-08 04:58