Object.values()

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

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

Try it

语法

¥Syntax

js
Object.values(obj)

参数

¥Parameters

obj

一个东西。

返回值

¥Return value

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

¥An array containing the given object's own enumerable string-keyed property values.

描述

¥Description

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

¥Object.values() returns an array whose elements are values of enumerable string-keyed properties 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.values() is the same as that provided by a for...in loop.

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

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

示例

¥Examples

使用 Object.values()

¥Using Object.values()

js
const obj = { foo: "bar", baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

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

// Array-like object with random key ordering
// When using numeric keys, the values are returned in the keys' numerical order
const arrayLikeObj2 = { 100: "a", 2: "b", 7: "c" };
console.log(Object.values(arrayLikeObj2)); // ['b', 'c', 'a']

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

在基元上使用 Object.values()

¥Using Object.values() 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.values("foo")); // ['f', 'o', 'o']

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

规范

Specification
ECMAScript Language Specification
# sec-object.values

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看