js中通过document.getElementById()获取到的值的类型

  • 问题描述:
var value1 = document.getElementById(“num1”).value; //3或9
var value2 = document.getElementById(“num2”).value; //4或10 
if(value1 < value2 ){
alert("正确")
}else{
alert("失败)
} 

当value1 = 3,value2 = 4的时候,弹出:正确;

当value1 = 9,value2 = 10的时候,弹出:失败;

  • 原因:
JS是 弱类型语言 ,变量的类型不是固定的,可以随时根据环境变化,JS运行时会自动根据当前的一些情况进行隐式转换。string类型是无法比较的。
value1 和value2得到的都是string类型的数据,string类型比较的时候 系统比对的是unicode编码的值,出现什么结果都是有可能的。所以js中有比较,最好先进行转换。

可以通过以下方式,判断js中数据的类型,在前端的控制台(console)中可以看到。
console . log ( typeof value1 );
console . log ( typeof value2 );

猜你喜欢

转载自blog.csdn.net/weixin_35703883/article/details/80974697