Object.values():以數組形式返回給定對象可枚舉屬性的值,如:[ 值1,值2,值3,值4 ]
舉例如下:
//對象
let obj1 = {one:'a',two:'b',three:'c'};
Object.values(obj1); // ["a", "b", "c"]
//鍵爲數字的對象,注意:此時會按照數字鍵的順序輸出
let obj2 = {1:'one',3:'tree',2:'two'};
Object.values(obj2); // ["one", "two", "tree"]
//數組
let obj3 = ['1','2','3'];
Object.values(obj3); // ["1", "2", "3"]
//字符串
Object.values('abcd'); // ["a", "b", "c", "d"]
Object.values():以數組形式返回給定對象可枚舉屬性的 [鍵:值],如:[ [鍵1,值1],[鍵2,值2],[鍵3,值3],[鍵4,值4] ]
Object.fromEntries():對Object.values()反向操作,將 [ [鍵1,值1],[鍵2,值2],[鍵3,值3],[鍵4,值4] ] 轉爲{鍵1:值1,鍵2:值2,鍵3:值3,鍵4:值4}
舉例如下:
//對象
let obj1 = {one:'a',two:'b',three:'c'};
Object.entries(obj1); // [["one", "a"],["two", "b"],["three", "c"]]
//Object.fromEntries()對Object.entries()反向操作
Object.fromEntries([["one", "a"],["two", "b"],["three", "c"]]); //{one: "a", two: "b", three: "c"}
//鍵爲數字的對象,注意:此時會按照數字鍵的順序輸出
let obj2 = {1:'one',3:'tree',2:'two'};
Object.entries(obj2); //[["1", "one"],["2", "two"],["3", "tree"]]
//Object.fromEntries()對Object.entries()反向操作
Object.fromEntries([["1", "one"],["2", "two"],["3", "tree"]]); //{1: "one", 2: "two", 3: "tree"}
//數組,注意:此時將數組['1','2','3']當作含數字鍵的對象{0:'1',1:'2','2','3'}
let obj3 = ['1','2','3'];
Object.entries(obj3); // [["0", "1"],["1", "2"],["2", "3"]]
//Object.fromEntries()對Object.entries()反向操作
Object.fromEntries([["0", "1"],["1", "2"],["2", "3"]]); //{0: "1", 1: "2", 2: "3"}
//字符串,同數組
Object.entries('abcd'); // [["0", "a"],["1", "b"],["2", "c"],["3", "d"]]
//Object.fromEntries()對Object.entries()反向操作
Object.fromEntries([["0", "a"], ["1", "b"], ["2", "c"], ["3", "d"]]); //{0: "a", 1: "b", 2: "c", 3: "d"}