之前看书的时候把Object.keys()属性貌似遗漏了,最近做题遇到了,记个笔记。Object.keys()是将对象中的键值(key)转化为数组的方法,然后再运用数组的方法。
(1)对象字面量创建对象
var data = {‘a’:1,’b’:2,’c’:3,’d’:a4};
console.log(Object.keys(data));
//输出为[‘a’,’b,’c’,’d’]
如果要输出data中value小于3的,可以用filter函数
var arr = Object.keys(data).filter(function(item){return data[item]<3});
console.log(arr);
//输出为[‘a’,’b’]。
(2)构造函数创建对象
function A(name,age,city){
this.name = name;
this.age = age;
this.city = city;
this.toString = function(){
return (this.name + ‘,’ +this.age +’,’ +this.city);
}
}
var B = new A(‘Juno’,’25’,’Wuhan’);
var arr2 = Object.keys(B);
console.log(arr2)
//输出为[‘name’,’age’,’city’,’toString’]
var keys = Object.keys(B).filter(check);
console.log(keys);
//check name 中的首字母是否为’n’
function check(value) {
var firstChar = B[value].substr(0, 1);
if (firstChar.toLowerCase() == “n”)
return true;
else
return false;
}