當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


JavaScript Object.entries()用法及代碼示例


JavaScript Object.entries() 方法返回對象的可枚舉屬性的鍵值對數組。

用法:

Object.entries(obj)

entries() 方法是靜態方法,使用Object 類名調用。

entries()參數

entries() 方法包含:

  • obj - 要返回其可枚舉的string-keyed 屬性鍵和值對的對象。

entries() 的返回值

  • 返回給定對象自己的可枚舉string-keyed屬性的數組[核心價值]對。

注意:屬性的順序與使用手動循環它們時的順序相同for...in環形。

示例:使用對象。entries()

const obj = { name: "Adam", age: 20, location: "Nepal" };
console.log(Object.entries(obj)); // [ [ 'name', 'Adam' ], [ 'age', 20 ], [ 'location', 'Nepal' ] ]

// Array-like objects
const obj1 = { 0: "A", 1: "B", 2: "C" };
console.log(Object.entries(obj1)); // [ [ '0', 'A' ], [ '1', 'B' ], [ '2', 'C' ] ]

// random key ordering
const obj2 = { 42: "a", 22: "b", 71: "c" };
// [ [ '22', 'b' ], [ '42', 'a' ], [ '71', 'c' ] ] -> arranged in numerical order of keys
console.log(Object.entries(obj2));

// string -> from ES2015+, non objects are coerced to object
const string = "code";
console.log(Object.entries(string)); // [ [ '0', 'c' ], [ '1', 'o' ], [ '2', 'd' ], [ '3', 'e' ] ]

// primite types have no properties
console.log(Object.entries(55)); // []

// Iterating through key-value of objects
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key}: ${value}`);
}

輸出

[ [ 'name', 'Adam' ], [ 'age', 20 ], [ 'location', 'Nepal' ] ]
[ [ '0', 'A' ], [ '1', 'B' ], [ '2', 'C' ] ]
[ [ '22', 'b' ], [ '42', 'a' ], [ '71', 'c' ] ]
[ [ '0', 'c' ], [ '1', 'o' ], [ '2', 'd' ], [ '3', 'e' ] ]
[]
name: Adam
age: 20
location: Nepal

相關用法


注:本文由純淨天空篩選整理自 Javascript Object.entries()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。