未捕获的 TypeError: Object.values 不是函数 JavaScript

我有一个像下面这样的简单物体:

var countries = {
"Argentina":1,
"Canada":2,
"Egypt":1,
};

我需要创建两个数组。第一个数组是对象中所有键的数组。我通过以下方法创建了这个数组:

var labels = Object.keys(countries);

这很有效。我得到了一个国家数组。现在,当我试图从这些值创建一个数组时..。

var labels = Object.values(countries);

我得到这个错误: Uncaught TypeError: Object.values is not a function JavaScript

我不知道我哪里做错了。声明 labels之前和之后的 console.log countries,对象保持不变。如何正确使用 Object.values()

107455 次浏览

.values is unsupported in many browsers - you can use .map to get an array of all the values:

var vals = Object.keys(countries).map(function(key) {
return countries[key];
});

See MDN doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values or Official doc: https://tc39.github.io/ecma262/#sec-object.values (thanks @evolutionxbox for correction)

Looks like this issue is fixed in Safari latest version. I came around the same issue. This issue occurs in browser version 9.0.1 and does not occur in 10.1.1

Editing to add the attachments:

[snippet][1]
[object value][2]
[browser version][3]

Using "for...in" as discussed at mozilla: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

Here is the code I used:

function objectValues(obj) {
let vals = [];
for (const prop in obj) {
vals.push(obj[prop]);
}
return vals;
}


// usage
let obj = {k1: 'v1', k2: 'v1', k3: 'v1'};


console.log(objectValues(obj));             // prints   the array  [ 'v1', 'v1', 'v1' ]
// OR
console.log(objectValues(obj).join(', '));  // prints   the string 'v1, v1, v1'

I think issue in compilation support on browsers compatibility, You can use map to achieve the same.

var countries = [
{
"Argentina": 1,
"Canada": 2,
"Egypt": 1,
"india": 1
},
{
"Argentina": 1,
"india": 1,
"US": 2,
"UK": 1,


}
];


var unpick = countries.map(d=>{ return Object.keys(d) });
console.log(unpick)

var countries = [
{
"Argentina": 1,
"Canada": 2,
"Egypt": 1,
"india": 1
},
{
"Argentina": 1,
"india": 1,
"US": 2,
"UK": 1,


}
];


var unpick = countries.map(d=>{ return Object.values(d) });
console.log(unpick)

It's also worth noting that only Node versions >= 7.0.0 fully support this.

http://node.green

For those who ended up here and are using Angular, adding import 'core-js/es7/object'; to polyfills.ts file solved the problem for me.

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/array';
import 'core-js/es6/date';
import 'core-js/es6/function';
import 'core-js/es6/map';
import 'core-js/es6/math';
import 'core-js/es6/number';
import 'core-js/es6/object';
import 'core-js/es6/parse-float';
import 'core-js/es6/parse-int';
import 'core-js/es6/regexp';
import 'core-js/es6/set';
import 'core-js/es6/string';
import 'core-js/es6/symbol';
import 'core-js/es6/weak-map';
import 'core-js/es7/array';
import 'core-js/es7/object'; // added import

Consider using _.values(object)

Docs: https://lodash.com/docs/4.17.11#values