1. js的几种数据类型
基本类型: number string boolean undefinded null
对象: object(包括function、array、date...)
js是一个弱类型语言,如下例子:
var a = 10 a = "string" // 虽然a定义为一个number 但是还是能赋值为string类型
2. js隐式转换
+ / - 转换
var num = 10 num + "24" = "1024" // 加字符串等于字符串拼接 num - '5' = 5 // 减会将字符串转为数字进行计算
== / === 转换
== 比较数值
- 字符串和数字比较,现将字符串转为数字,然后进行比较
- boolean和其他值比较时,先将boolean转换数字再进行比较
- 在js规范中提到null 和 undefined在比较相等性之前不能将其转换为任何值,规定他们是相等的,并且都代表无效值
- new object和数组[1,2] 都为引用类型,因此他们虽然值相等,但是指向不同,所以不相等
1.23 == "1.23" //true 0 == false // true null == undefined // true new Object() = new Object() // false [1,2] == [1,2]
=== 严格等于,首先会比较类型,类型相同再比较值
类型相同,和 == 一样
类型不同,返回false
需要注意的是NaN和任何值都不相等,甚至是它自己,NaN ≠ NaN
3. 包装类型
定义一个基本类型,需要以对象的方式去操作它的时候,js会将基本类型转换为包装类型,临时创建一个对象,临时操作后自动销毁
var a = "string" console.log(a.length) // 基本类型是没有length这个属性的,js自动处理为包装类选String,取其length a.t = 3; 给包装类型对象添加t属性 console.log(a.t) // undefined,已经销毁
4. 类型检测
typeof用于检测基本类型和function,但是不能检测null,typeof遇到null检测为object
typeof 100 // number typeof function // function typeof true // boolean typeof undefined //undefined typeof null // object typeof NaN // number typeof [1,2] // object typeof new Object() // object
Object.prototype.toString() 可用于判断基本类型、引用类型,但是在IE8以下,检测null 和 undefined会存在兼容性问题,斟酌使用~
Object.prototype.toString.apply([]) // [object, Array] Object.prototype.toString.apply(function() {}) // [object, Function] Object.prototype.toString.apply(null) // [object, Null] Object.prototype.toString.apply(undefined) // [object, Undefined]
Object对象上和原型链上都有一个toString()函数,第一个返回的是函数,第二个返回的是值类型,如下
[]数组本身继承自Array,Object.prototype.toString()返回的是 [object, object], 通过apply将Array的this上下文切换到了Object,调用了Object.prototype.toString(),返回了[object, Array]
instanceof 判断对象的特定类型,也可以说是判断对象是否继承自某个对象原型
obj instanceof Object instance的左子树和右子树都要为对象
function Person() {} function Student() {} Student.prototype = new Person() // Student继承Person Student.prototype.constructor = Student var jojo = new Student() var one = new Person() jojo instanceof Student // true Student为jojo的父级 one instanceof Person // true 同上 one instanceof Student // false one和Student同为Person的子级 jojo instanceof Person // true jojo继承自Student,Person为Student的父级