今天遇到个题目,说是用js读取我输入的值,然后判断数据类型。写的时候,发现如果使用prompt和input都会导致读取的结果是string类型的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<input type="text" id="inp1" />
<button id="btn">判断数据类型</button>
<input type="text" id="inp2" />
<script>
btn.onclick = function () {
var inp = inp1.value;
var a = Number(inp);
a++;
if (inp == "true" || inp == "false") {
inp = Boolean(inp);
inp2.value = "这个数据类型是Boolean";
} else if (inp == "" || inp == "Null" || inp == "null" || inp == " ") {
inp2.value = "空值";
} else if (inp == "undefined" || inp == "Undefined") {
inp2.value = "这个数据类型是undefined";
} else if (inp == "Object" || inp == "object") {
inp2.value = "这个数据类型是Object";
} else if (!isNaN(a)) {
inp2.value = "这个数据类型是数值型";
} else if (inp == "Symbol" || inp == "symbol") {
inp2.value = "这个数据类型是Symbol";
} else if (inp == "BigInt" || inp == "bigInt") {
inp2.value = "这个数据类型是BigInt";
} else {
inp2.value = "这个数据类型是String";
}
};
</script>
</body>
</html>