在 ES2017 (ES8) 中,Object 构造函数获得了两个新的有用方法:Object.values 和 Object.entries。 让我们快速回顾一下它们的使用。
对象值
Object.values 接受一个对象并返回一个包含值的数组,其顺序与 for...in 循环给我们的顺序相同。 例如:
const myObj = {
piggy: '🐷',
birdy: '🐦',
bunny: '🐰'
};
const myValues = Object.values(myObj); // ["🐷", "🐦", "🐰"]
Object.values 不遵循原型链,仅迭代直接在提供的对象上的值。 它也不会返回任何不可枚举的值,如下例所示:
const myObj = {
piggy: '🐷',
birdy: '🐦',
bunny: '🐰'
};
Object.defineProperty(myObj, 'koala', {
value: '🐨',
writable: true,
configurable: true,
enumerable: true
});
let myValues = Object.values(myObj); // ["🐷", "🐦", "🐰", "🐨"]
Object.defineProperty(myObj, 'koala', {
value: '🐨',
writable: true,
configurable: true,
enumerable: false
});
myValues = Object.values(myObj); // ["🐷", "🐦", "🐰"]
对象条目
与前面的方法非常相似,Object.entries 返回一个包含键值对数组的数组:
const moreAnimals = {
camel: '🐫',
boar: '🐗',
turkey: '🦃'
};
const entries = Object.entries(moreAnimals);
// [['camel','🐫'],['boar','🐗'],['turkey','🦃']]
由于新的 map 对象类型 可以使用 Object.entries 提供给我们的形状数组来初始化 ,因此现在很容易从目的:
const moreAnimals = {
camel: '🐫',
boar: '🐗',
turkey: '🦃'
};
const animalsMap = new Map(Object.entries(moreAnimals));
console.log(animalsMap.size); // 3
console.log(animalsMap.has('turkey')); // true
console.log(animalsMap.get('camel')); // '🐫'