对象相关
常用对象操作Api
for in
hasOwnProperty
(检查属性是不是对象自有的,排除从原型链找到的属性)
var obj = {
x: 10,
y: 20,
z: 30
}
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key + ':' + obj[key]);
}
}
Object.keys
// simple array
var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// array like object with random key ordering
var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']
// getFoo is a property which isn't enumerable
var myObj = Object.create({}, {
getFoo: {
value: function () { return this.foo; }
}
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']
判断对象属性是否存在
var myObj = {
top: "hat",
bottom: "pants"
};
myObj.hasOwnProperty("top"); // true
myObj.hasOwnProperty("middle"); // false
var myObj = {
top: "hat",
bottom: "pants"
};
'top' in myObj //true
'left' in myObj //false
判断Object是否为空
Object.keys(object).length === 0
JSON.stringify(object) === '{}'
Object.getOwnPropertyNames(obj)
//第三种方案是较为完善的,它不仅可以访问当前属性还可以访问非枚举属性