typeof和instanceof
typeof
typeof
是一个操作符,用来检测一个值的类型。它返回一个字符串,表示值的类型。
javascript
console.log(typeof 123); // number
console.log(typeof '123'); // string
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object ⭐
console.log(typeof {}); // object ️
console.log(typeof []); // object ⭐
instanceof
instanceof
是一个操作符,用来检测一个对象是否是另一个对象的实例。它返回一个布尔值。
javascript
console.log([] instanceof Array); // true
console.log([] instanceof Object); // true
console.log({} instanceof Object); // true
HasOwnProperty
Object
实例的hasOwnProperty()
方法返回一个布尔值,指示此对象是否具有指定的属性作为其自身的属性(而不是继承得来的)。
javascript
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// Expected output: true
console.log(object1.hasOwnProperty('toString'));
// Expected output: false
console.log(object1.hasOwnProperty('hasOwnProperty'));
// Expected output: false
应用:获取对象的所有属性
javascript
const map = {
a: {
b: {
c: 12
},
d: [12, 11],
f: () => { }
}
}
function getObjKeyPathMap(obj) {
const v = {}
function traverse(obj, path) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
const next = obj[key]
path = path ? path + '.' + key : key
if (typeof next === "object" && !Array.isArray(next)) {
traverse(next, path)
} else {
v[path] = next
}
}
}
}
traverse(obj)
return v
}
console.log(getObjKeyPathMap(map)); // { 'a.b.c': 12, 'a.d': [ 12, 11 ], 'a.f': [Function: f] }