js中的数据类型:
1)、基础数据类型
<1>数值 number (不分为整数类型和浮点型类型,所有的数字均是浮点型类型)
<2>字符串 string
<3>布尔值 boolean
<4>空类型 null(空)
<5>未定义类型 undefined
2)、复合数据类型(引用数据类型:引用的是地址)
Object—>包括数组(Array)、函数(function)、日期(Data)等
1、使用typeof能判断出6种,分别是number、string、boolean、undefined、object、function,剩余的均被检测为object 。需要注意的是,typeof返回的都是字符串。
2、instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。判断已知对象类型的方法。
3、constructor 属性返回对创建此对象的数据类型的引用。
4、Object.prototype.toString.call(xx) / Object.prototype.toString.apply(xx)
5、使用jquery的$.type()
6、如果是判断是不是数组,可以用 Array.isArray(xx)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
//1、
let num = 1
let str = '1'
let b = true
let u = undefined
let n = null
let arr = []
let obj = {}
let fun = function(){}
let date = new Date()
console.log(typeof num,typeof str,typeof b,typeof u,typeof n,typeof arr,typeof obj,typeof fun,typeof date)
//输出:number string boolean undefined object object object function object
//在 js 中,数组是一种特殊的对象类型。null 是一个只有一个值的特殊类型,表示一个空对象引用。所以都返回 object 。
//上面这些输出值都是字符串
//2、
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car); //true
console.log(num instanceof Number); //false
console.log(auto instanceof Object); //true
//3、
console.log(str.constructor) //ƒ String() { [native code] }
//4、
let oo = Object.prototype.toString.call(u)
let xx = Object.prototype.toString.apply(b)
console.log(oo,xx) //[object Undefined] [object Boolean]
//5、使用jquery的$.type
//$.type()是基于ES5的Object.prototype.toString.call()进一步封装。
</script>
</body>
</html>