使用instanceof判断对象的类型
typeof和instanceof的区别:
typeof可以判断任意变量的类型,在判断对象类型的适合,typeof总是返回object
instanceof只能判断对象的类型,判断对象的精确类型时,返回true或者false
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var nums = [12, 4, 54];
var stu = {
id: 1001,
name: "jack"
};
var p = new Person("alice", 20);
console.log(nums instanceof Array);
console.log(nums instanceof Person);
console.log(stu instanceof Person);
console.log(p instanceof Person);
if (stu instanceof Array) {
console.log("stu是一个数组");
}
function Person(name, age) {
this.name = name;
this.age = age;
}
</script>
</head>
<body>
</body>
</html>