例子
var a = 123
var b = 'apple'
var c = true
var d = null
var e = undefined
var f = [1, 2, 3]
var g = { name: 'lisi', age: 21 }
var h = function () {
return 1 + 2
}
var i = /test/
var j = new Date()
var k = new Set([1, 2, 3, 4])
var l = new Map([
['name', '张三'],
['title', 'Author']
])
function Animal() {
}
1、typeof
console.log(typeof a);
console.log(typeof b);
console.log(typeof c);
console.log(typeof d);
console.log(typeof e);
console.log(typeof f);
console.log(typeof g);
console.log(typeof h);
console.log(typeof i);
console.log(typeof j);
console.log(typeof (typeof a));
2、instanceof
console.log(f instanceof Array);
console.log(f instanceof Object);
console.log(f instanceof Animal);
console.log(h instanceof Function);
3、根据对象的constructor判断
console.log(f.constructor === Array);
console.log(g.constructor === Object);
console.log(h.constructor === Function);
4、Object.prototype.toString.call()
console.log(Object.prototype.toString.call(a) === '[object Number]');
console.log(Object.prototype.toString.call(b) === '[object String]');
console.log(Object.prototype.toString.call(c) === '[object Boolean]');
console.log(Object.prototype.toString.call(d) === '[object Null]');
console.log(Object.prototype.toString.call(e) === '[object Undefined]');
console.log(Object.prototype.toString.call(f) === '[object Array]');
console.log(Object.prototype.toString.call(g) === '[object Object]');
console.log(Object.prototype.toString.call(h) === '[object Function]');
console.log(Object.prototype.toString.call(j) === '[object Date]');
5、万能jQuery.type()方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
</head>
<body>
</body>
<script>
var a = 123
var b = 'apple'
var c = true
var d = null
var e = undefined
var f = [1, 2, 3]
var g = { name: 'lisi', age: 21 }
var h = function () {
return 1 + 2
}
var i = /test/
var j = new Date()
var k = new Set([1, 2, 3, 4])
var l = new Map([
['name', '张三'],
['title', 'Author']
])
function Animal() {}
console.log(jQuery.type(a));
console.log(jQuery.type(b));
console.log(jQuery.type(c));
console.log(jQuery.type(d));
console.log(jQuery.type(e));
console.log(jQuery.type(f));
console.log(jQuery.type(g));
console.log(jQuery.type(h));
console.log($.type(i));
console.log($.type(j));
console.log(jQuery.type(k));
console.log(jQuery.type(l));
</script>
</html>
|