ES7 Object.keys,Object.values,Object.entries

豬豬是天才發表於2018-11-09

1.Object.keys

var obj = { foo: "bar", baz: 42 };
Object.keys(obj)
// ["foo", "baz"]複製程式碼


2.Object.values

var obj = { 100: 'a', 2: 'b', 7: 'c' };
Object.values(obj)
// ["b", "c", "a"]複製程式碼


3.Object.entries

let obj = { a: 1, b: 2, c: 3 };  
Object.entries(obj)
// [["a", 1], ["b", 2], ["c", 3]]複製程式碼


4.三種同時使用,簡便寫法

let {keys, values, entries} = Object;  

let obj = { a: 1, b: 2, c: 3 };  

for (let key of keys(obj)) {  
    console.log(key); // 'a', 'b', 'c'  
}  

for (let value of values(obj)) {  
    console.log(value); // 1, 2, 3  
}  

for (let [key, value] of entries(obj)) {  
    console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3]  
} 複製程式碼


相關文章