JS函数之判断数据类型代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS函数之判断数据类型代码</title>
</head>
<body>
/******************* JS函数之判断数据类型代码 **********************/
<script>
//定义变量
var a=1, b, c=null, d=[], e={};
//声明getType函数
function getType(x){
//利用typeof判断数据类型,得到number类型、undefinded类型、object类型
if(typeof x == 'object'){
// //使用instanceof判断某变量是否属于某对象
if(x instanceof Array){
//返回结果
return 'array';
}else if(x instanceof Object){
return 'object';
}else{
return 'null';
}
}else{
//返回数据类型
return typeof x;
}
}
// 调用函数并输出
console.log(getType(e));
</script>
</body>
</html>