Open goldEli opened 4 years ago
[x] 判断基本数据类型的时候可以使用typeof()函数来判断,但是由于null,[],{}使用typeof()函数判断均返回object,因此需要使用其他方法来进行判断 undefined:是所有没有赋值变量的默认值,自动赋值。 null:主动释放一个变量引用的对象,表示一个变量不再指向任何对象地址(一般用于释放对象的内存)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>判断变量的数据类型</title>
</head>
<body>
<script>
/**
* 判断变量类型
* @param {any}
* @return {string}
*/
function jugementType(variable) {
if(typeof(variable) != "object"){
return "变量的类型为:" + typeof (variable);
}
if(!(variable instanceof Object)){
return "变量的类型为:null";
}
if(Array.isArray(variable)){
return "变量的类型为:数组";
}else{
return "变量的类型为:对象";
}
};
var tmp = null;
jugementType(tmp);
</script>
</body>
</html>
JS基本有5种简单数据类型:String,Number,Boolean,Null,undefined,Symbol(独一无二的值)。 引用数据类型Object,Array,Fuction
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>judge type</title>
</head>
<body>
<script>
/**
* 判断变量类型
* @param {any}
* @return {string}
*/
function jugementType(variable) {
switch(Object.prototype.toString.call(variable)){
case '[object Number]':
return 'number'; break;
case '[object String]':
return 'string'; break;
case '[object Boolean]':
return 'boolean'; break;
case '[object Array]':
return 'array'; break;
case '[object Object]':
return 'object'; break;
case '[object Function]':
return 'function'; break;
case '[object Undefined]':
return 'undefined'; break;
case '[object Null]':
return 'null'; break;
case '[object Date]':
return 'date'; break;
case '[object RegExp]':
return 'regExp'; break;
case '[object Error]':
return 'error';
}
}
// 比如
console.log(jugementType(3));
console.log(jugementType('3'));
console.log(jugementType({}));
console.log(jugementType([]));
</script>
</body>
</html>
简单数据类型:String,Number,Boolean,Null,undefined,Symbol(独一无二的值)。 引用数据类型Object,Array,Fuction
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
var a = Object.prototype.toString;
function jugementType(variable) {
console.log(a.call(variable));
}
// 比如
jugementType(3) // number
jugementType('3') // string
jugementType({}) // object
jugementType([]) // array
jugementType(null) // array
</script>
</html>