一、Object.keys(obj)
let person = {name:"张三",age:25,address:"深圳",getName:function(){}};
console.log(Object.keys(person));
let arr = [1,2,3,4,5,6];
console.log(Object.keys(arr)); //["0", "1", "2", "3", "4", "5"]
let str = "ikun你好";
console.log(Object.keys(str)); // ["0", "1", "2", "3", "4", "5"]
let person = {name:"张三",age:25,address:"深圳",getName:function(){}};
Object.keys(person).map((key)=>{
console.log(person[key]); // 获取到属性对应的值,做一些处理
})
二、Object.values()
let obj = {
foo : "bar",
baz : 20
};
console.log(Object.values(obj)); // ["bar", 20]
const obj = {100 : "a", 2 : "b", 7 : "c"};
console.log(Object.values(obj)); //["b", "c", "a"]
const obj = Object.create({},{p : {value : 10}});
console.log(Object.values(obj));
console.log(Object.getOwnPropertyDescriptors(obj));
因此只要把enumerable改成true,Object.values就会返回属性p的值。
const obj = Object.create({},{p:{
value : 10,
enumerable : true,
configurable : true,
writable : true,
}})
console.log(Object.values(obj)); //[10]
//如果Object.values方法的参数是一个字符串,会返回各个字符组成的一个数组。
Object.values({ [Symbol()]: 123, foo: 'abc' });
console.log(Object.values('foo')); //["f", "o", "o"]
console.log(Object.values(42)); // []
console.log(Object.values(true)); // []
console.log(Object.values(undefined)); //error
console.log(Object.values(null)); //error
三、Object.entries()
var obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj));
console.log(Object.entries({ [Symbol()]: 123, foo: 'abc' })); // [ [ 'foo', 'abc' ] ]
let obj = {
one : 1,
two : 2,
}
for(let [k , v] of Object.entries(obj)){
console.log(`${JSON.stringify(k)} : ${JSON.stringify(v)}`);
}
const obj = {foo : "bar", baz : 10};
const map = new Map(Object.entries(obj));
console.log(map);
const entries = (obj) => {
let result = [];
const objType = typeof(obj);
if(obj === undefined || obj === null){
throw new TypeError();
}
if(objType === "number" || objType === "boolean"){
return [];
}
for(let k of Object.keys(obj)){
result.push([k,obj[k]]);
}
return result
}