JavaScript Object.entries()

Object.entries() 方法返回一个对象可枚举属性的键值对数组。

示例

const obj = { name: "Adam", age: 20, location: "Nepal" };

// returns properties in key-value format
console.log(Object.entries(obj)); 

// Output:  [ [ 'name', 'Adam' ], [ 'age', 20 ], [ 'location', 'Nepal' ] ]

entries() 语法

entries() 方法的语法是

Object.entries(obj)

entries() 方法是静态方法,通过 Object 类名调用。


entries() 参数

entries() 方法接受

  • obj - 要返回其可枚举属性的对象。

entries() 返回值

entries() 方法返回一个包含对象所有可枚举属性的数组,其中每个元素都是一个键值对。


示例 1:JavaScript Object.entries()

let student= {
  name: "Lida",
  age: 21
};

// convert student's properties // into an array of key-value pairs let entries = Object.entries(student);
console.log(entries); // Output:[ [ 'name', 'Lida' ], [ 'age', 21 ] ]

在上面的示例中,我们创建了一个名为 student 的对象。然后,我们使用 entries() 方法以键值对格式获取其可枚举属性。

注意:可枚举属性是在 for...in 循环和 Object.keys() 中可见的属性。


示例 2:带随机键的 entries()

// keys are arranged randomly
const obj = { 42: "a", 22: "b", 71: "c" };

// returns key-value pairs arranged // in ascending order of keys console.log(Object.entries(obj));
// Output: [ [ '22', 'b' ], [ '42', 'a' ], [ '71', 'c' ] ]

在上面的示例中,我们创建了一个 obj 对象,其键是随机排列的,即它们没有顺序(升序或降序)。

但是,如果我们在 obj 上使用 entries() 方法,输出将包含键值对,其中键按升序排序。


示例 3:使用 entries() 遍历键值对

const obj = { name: "John", age: 27, location: "Nepal" };

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

输出

name: John
age: 27
location: Nepal

在上面的示例中,我们在 for 循环中使用 entries() 方法来遍历 obj 对象。

在循环的每次迭代中,我们可以以键值对的形式访问当前对象属性。


示例 4:字符串的 entries()

const str = "code";

// use entries() with the above string console.log(Object.entries(str));
// Output: [ [ '0', 'c' ], [ '1', 'o' ], [ '2', 'd' ], [ '3', 'e' ] ]

在上面的示例中,我们对 str 字符串使用了 entries() 方法。这里,输出的每个元素包括

  • key - 字符串中每个字符的索引
  • value - 相应索引处的单个字符

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战