JS数据类型检测
- typeof typeof可以判断undefined、Boolean、number、string、function、以及构造函数判断为function;
注意: NaN是Number类型
但是typeof判断数组、对象和null的时候都为object。
- instanceof instanceof只能判断应用数据类型,常用于检测一个对象是否为另一个构造函数的实例。
注意: 在instanceof检测符中所有引用类型都是Object的实例
// eg
const a = [1,2,3]
a instanceof Object // => 打印会输出true
- Object.prototype.toString.call() 每个引用类型自身的toString方法只会将其转换为字符串; Object.prototype上的toString方法却会输出其数据类型。
// eg
const a = [1,2,3]
Object.prototype.toString.call(a) // => 打印会输出 '[object Array]'
数据类型小练习
- 判断一个数据是否为对象
function isObject(data){
// 首先判断引用数据类型
if(typeof data === 'object' && data !==null){
// 判断数组和对象
// 方式1
if(Array.isArray(data)) return false
// 方式2
if(data instanceof Array)return false
// 方式3
if(Object.prototype.toString.call(data).slice(8,-1)==='Array')return false
return true
}
return false
}
- 判断一个数据是否为数组
// 与上面有所重复
function isArray(data){
// 方式1
return Array.isArray(data)
// 方式2
return data instanceof Array
// 方式3
return Object.prototype.toString.call(data).slice(8,-1)==='Array'
}
- 判断一个数据是否为NaN NaN(不是一个数字且数据类型为number,另外NaN != NaN)是执行数学运算没有成功,返回失败的结果。但是这个结果仍然是数字类型。
// 方式一(根据定义结合原生isNaN方法)
function judgeNaN(data){
return typeof data === 'number' && isNaN(data)
}
function judgeNaN(data){
return data !== data
}
function judgeNaN(data){
return Object.is(data,NaN)
}
- 判断一个数据是否为null
function judge(data){
return data === null
}
基于数据类型检测实现深拷贝
const a = {
base: 1,
fuza: {
a: 1,
b: 2
},
c:[{a: 1, b: 2, c: 3}]
}
// 深拷贝函数
function deepClone(object) {
// 注意块级作用域,这样声明是错误的,在下面for循环中不能访问res
// if(typeof object === 'object' && object !== null){
// if(Array.isArray(object)){
// const res = []
// }else{
// const res = {}
// }
// }
let res = {}
if(typeof object === 'object' && object !== null){
if(Array.isArray(object)){
res = []
}
}
// 此处使用for in 循环,是为了对于数组和对象都适用
for (const key in object) {
if (typeof object[key] === 'object' && object[key] !== null) {
res[key] = deepClone(object[key])
} else {
// 基础数据类型和函数直接赋值
res[key] = object[key]
}
}
return res
}
// 调用
console.log(deepClone(a))