一、js数据类型
基本数据类型:String、Number、Boolean、Null、Undefined
复杂数据类型:Object
二、js数据类型判断
let str = "字符串类型"
let bool = true
let num = 123
let nulll = null
let undef
let arr = []
let obj = {}
let sum = function () {}
1. 使用typeof进行判断
console.log(typeof str) // string
console.log(typeof bool) // boolean
console.log(typeof num) // number
console.log(typeof nulll) // object
console.log(typeof undef) // undefined
console.log(typeof arr) // object
console.log(typeof obj) // object
console.log(typeof sum) // function
使用typeof进行判断数据类型,只能够判断基本数据类型string number boolean 以及 function,而null和object不能够进一步的判断。
2. 使用A instanceof B进行判断
console.log(str instanceof String) // false
console.log(bool instanceof Boolean) // false
console.log(num instanceof Number) // false
console.log(nulll instanceof Object) // false
console.log(undef instanceof Object) // false
console.log(arr instanceof Array) // true
console.log(obj instanceof Object) // true
console.log(sum instanceof Function) // true
使用A instanceof B的方式进行判断,字面意思,A是否是B的实例,可以判断出Array和Object类型,但是undefined和null不能区分数据类型,基础的数据类型,因为不是使用new出来的,也测试不出来。
3. 使用Object.prototype.toString.call()进行判断
console.log(Object.prototype.toString.call(str)) // [object String]
console.log(Object.prototype.toString.call(bool)) // [object Boolean]
console.log(Object.prototype.toString.call(num)) // [object Number]
console.log(Object.prototype.toString.call(nulll)) // [object Null]
console.log(Object.prototype.toString.call(undef)) // [object Undefined]
console.log(Object.prototype.toString.call(arr)) // [object Array]
console.log(Object.prototype.toString.call(obj)) // [object Object]
console.log(Object.prototype.toString.call(sum)) // [object Function]
Object.prototype.toString()方法可以返回一个表示该对象的字符串'[object type]',为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象作为第一个参数,称为 thisArg。
三、实现深拷贝函数
function deepClone(ob) {
if (typeof ob === "object") {
if (Object.prototype.toString.call(ob).slice(8, -1) === 'Null') return ob
if (ob instanceof Array) {
// 数组
let newArr = []
ob.forEach((item, index, arr) => {
newArr[index] = deepClone(item)
})
return newArr
} else {
// 对象
let newObj = {}
// for (let k in ob) {
// newObj[k] = deepClone(ob[k])
// }
Object.keys(ob).forEach((key, index, arr) => {
newObj[key] = deepClone(ob[key])
})
return newObj
}
} else {
return ob
}
}
实现思路:
- 先判断是不是对象类型的,不是对象类型,直接返回出去
- 如果是对象类型的话,再判断是对象还是数组
- 对对象或者数组进行遍历,对值进行递归
其实还有很多深拷贝的方式,比如说Object.assign(),JSON.stringify()等方式,可以自己下去尝试一下哦!
网友评论