1. 判断是否为对象
1 2
| Object.prototype.toString.call({}) === '[object Object]' Object.prototype.toString.call([]) === '[object Array]'
|
2. 判断对象是否全等
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const isObjectValueEqual = (a, b) => { const aProps = Object.getOwnPropertyNames(a) const bProps = Object.getOwnPropertyNames(b) if (aProps.length !== bProps.length) { return false } for (let i = 0; i < aProps.length; i++) { const propName = aProps[i] const propA = a[propName] const propB = b[propName] if (!Object.prototype.hasOwnProperty.call(b, propName)) return false if ((propA instanceof Object)) { if (!isObjectValueEqual(propA, propB)) { return false } } else if (propA !== propB) { return false } } return true }
|
3. 获取对象全部属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| obj = { weixinSecret: '', Appid: '', Desc: '', channelId: 0 } console.info(Object.keys(obj)) console.info(Object.getOwnPropertyNames(obj))
for(a in obj) { console.info(a) }
for(a of obj) { console.info(a) }
|
4. 合并对象属性
1 2
| obj = Object.assign(obj, {Desc: 'aaa', ChannelName: ''})
|
5. 判断对象是否为空
JavaScript 中如何判断对象是否为空 - 掘金 (juejin.cn)
1 2 3 4 5 6 7 8 9 10
| const obj = {}
!Boolean(obj)
JSON.stringify(obj)==='{}' JSON.stringify({name: function() {a: 'eee'}})
obj && Object.keys(obj).length === 0 && obj.constructor === Object
|
6. 判断对象是否存在某属性
1 2
| var obj = { name: '小明' } obj.hasOwnProperty('name')
|