Object.keys()

Object.keys() 静态方法返回给定对象自己的可枚举字符串键控属性名称的数组。

¥The Object.keys() static method returns an array of a given object's own enumerable string-keyed property names.

Try it

语法

¥Syntax

js
Object.keys(obj)

参数

¥Parameters

obj

一个东西。

返回值

¥Return value

表示给定对象自己的可枚举字符串键控属性键的字符串数组。

¥An array of strings representing the given object's own enumerable string-keyed property keys.

描述

¥Description

Object.keys() 返回一个数组,其元素是与直接在 object 上找到的可枚举字符串键控属性名称相对应的字符串。这与使用 for...in 循环进行迭代相同,只是 for...in 循环也会枚举原型链中的属性。Object.keys() 返回的数组的顺序与 for...in 循环提供的数组的顺序相同。

¥Object.keys() returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon object. This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well. The order of the array returned by Object.keys() is the same as that provided by a for...in loop.

如果你需要属性值,请改用 Object.values()。如果你同时需要属性键和值,请改用 Object.entries()

¥If you need the property values, use Object.values() instead. If you need both the property keys and values, use Object.entries() instead.

示例

¥Examples

使用 Object.keys()

¥Using Object.keys()

js
// Simple array
const arr = ["a", "b", "c"];
console.log(Object.keys(arr)); // ['0', '1', '2']

// Array-like object
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.keys(obj)); // ['0', '1', '2']

// Array-like object with random key ordering
const anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.keys(anObj)); // ['2', '7', '100']

// getFoo is a non-enumerable property
const myObj = Object.create(
  {},
  {
    getFoo: {
      value() {
        return this.foo;
      },
    },
  },
);
myObj.foo = 1;
console.log(Object.keys(myObj)); // ['foo']

如果你想要所有字符串键控自己的属性,包括不可枚举的属性,请参阅 Object.getOwnPropertyNames()

¥If you want all string-keyed own properties, including non-enumerable ones, see Object.getOwnPropertyNames().

在基元上使用 Object.keys()

¥Using Object.keys() on primitives

非对象参数是 强制对象undefinednull 不能被强制为对象并预先抛出 TypeError。只有字符串可以拥有自己的可枚举属性,而所有其他原语都返回空数组。

¥Non-object arguments are coerced to objects. undefined and null cannot be coerced to objects and throw a TypeError upfront. Only strings may have own enumerable properties, while all other primitives return an empty array.

js
// Strings have indices as enumerable own properties
console.log(Object.keys("foo")); // ['0', '1', '2']

// Other primitives except undefined and null have no own properties
console.log(Object.keys(100)); // []

注意:在 ES5 中,将非对象传递给 Object.keys() 会抛出 TypeError

¥Note: In ES5, passing a non-object to Object.keys() threw a TypeError.

规范

Specification
ECMAScript Language Specification
# sec-object.keys

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看