Object.values()
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()
非对象参数会被强制转换为对象。 undefined 和 null 不能被强制转换为对象,并会立即抛出 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 |
浏览器兼容性
加载中…