Object.values()

Baseline 已廣泛支援

此特性已得到良好確立,可跨多種裝置和瀏覽器版本使用。自 2017 年 3 月起,所有瀏覽器均支援此特性。

Object.values() 靜態方法返回給定物件自身可列舉的字串鍵屬性值組成的陣列。

試一試

const object = {
  a: "some string",
  b: 42,
  c: false,
};

console.log(Object.values(object));
// Expected output: Array ["some string", 42, false]

語法

js
Object.values(obj)

引數

obj

一個物件。

返回值

包含給定物件自身可列舉的字串鍵屬性值的一個數組。

描述

Object.values() 返回一個數組,其元素是直接在 object 上找到的可列舉字串鍵屬性的值。這與使用 for...in 迴圈進行迭代相同,不同之處在於 for...in 迴圈還會列舉原型鏈中的屬性。Object.values() 返回的陣列順序與 for...in 迴圈提供的順序相同。

如果您需要屬性鍵,請使用 Object.keys()。如果您同時需要屬性鍵和值,請使用 Object.entries()

示例

使用 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()

非物件引數會被強制轉換為物件undefinednull 不能被強制轉換為物件,並會立即丟擲 TypeError。只有字串可以擁有自身的列舉屬性,而所有其他原始值都會返回一個空陣列。

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)); // []

規範

規範
ECMAScript® 2026 語言規範
# sec-object.values

瀏覽器相容性

另見