一、组数据类型判断方式
1.Object.prototype.toString.call();
const arr = [1,2,3];
console.log(Object.prototype.toString.call(arr)); // '[object Array]'
2.target instanceof Array
const arr = [1,2,3];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true
instanceof 值得注意的是,这个只能用于判断对象,且所有的对象类型都会返回true
3.Array.isArray()
const arr = [1,2,3];
console.log(Array.isArray(arr)); // true
Array.isArray() ES5新增方法,其中还有Array.form(),转换数据为数组,根据转换的数据内部是否有length属性。
二、typeof
typeof 'name' // 'string'
typeof undefined // 'undefined'
typeof get() // 'function'
typeof 123 // 'number'
typeof true // 'boolean'
typeof null // 'object'
typeof {} // 'object'
typeof [] // 'object'
三、对象的几个方法
1.Object.defineProperty()
const objs = {}
Object.defineProperty(objs, 'name', {
value: 1,
configurable: true, // 是否可以被删除,已经其他配置属性是否可以被修改
writable: true, // 是否可以写,就是能不能修改
enumerable: true, // 是否可以枚举,就是能不能遍历,for in 这样的
});
console.log(objs.name); // 1
这个里面还有get/set方法,实际也就是getter/setter(访问器),不过不能和value,还有writable属性同时存在。
const objs = {}
Object.defineProperty(objs, 'name', {
// value: 1,
configurable: true, // 是否可以被删除,已经其他配置属性是否可以被修改
// writable: true, // 是否可以写,就是能不能修改
enumerable: true, // 是否可以枚举,就是能不能遍历,for in 这样的
get(){return '123'}, // 读取name的时候,写get 就会走着地方,相当于做了一层拦截,vue2.x里面的双向数据绑定原理,就用了这个
// 还有set 赋值,不过咱们一般就直接赋值了
});
console.log(objs.name); // 123
值得注意的是,这个实际也是vue2.x双向数据绑定的实现原理之一。3.x版本换成了 Proxy自动代理了,有兴趣的去官网看看。
2.Object.defineProperties(obj,props)
const obj = {}
Object.defineProperties(obj, {
name: {
value: 1,
configurable: true,
writable: true,
enumerable: true,
},
age: {
// value: 1,
configurable: true, // 是否可以被删除,已经其他配置属性是否可以被修改
// writable: true, // 是否可以写,就是能不能修改
enumerable: true, // 是否可以枚举,就是能不能遍历,for in 这样的
get() {
return '123'
},
}
});
console.log(obj.name); // 1
console.log(obj.age); // 123
实际用法和上面的一样,就是这个可以同时处理多个属性,属性方面都一样。
3.hasOwnProperty()
这个在进行比较大的逻辑函数封装的时候,会用,判断对象是有某个属性,只会查询自身,不会查到原型链里面去。(原型链的知识,也可以去看看)。
const obj = {name:'tom'};
console.log(obj.hasOwnProperty('name')); // true
比较基础的用法,就是深拷贝里面可以用。
4.proxy(了解)
const target = {}
const proxys = new Proxy(target,{
get:(tarpTarget,propKey,receiver)=>{
if(tarpTarget[propKey]){
return tarpTarget[propKey]
}else{
throw new TypeError('没有这个属性')
}
},
set:(tarpTarget,propKey,value,receiver)=>{
return Reflect.set(tarpTarget,propKey,value,receiver)
}
});
proxys.name = 'tom';
console.log(target.name); // 'tom'
console.log(target.age); // undefined
console.log(proxys.age); // 报错,没有这个属性
Proxy是新增的一个,代理,vue3.x双向数据绑定的原理,就有它,需要注意的是,这种写法,直接访问target是没有走拦截器,只有通过proxys去访问才会走,有兴趣的可以看看官网介绍。
本来还有一点ES6的方法,后面再写, 也不能一直摸鱼,哈哈