未捕获的 TypeError:Object.values 不是函数 JavaScript
我有一个像下面这样的简单对象:
I have a simple object like the one below:
var countries = {
"Argentina":1,
"Canada":2,
"Egypt":1,
};
我需要创建两个数组.第一个数组是对象中所有键的数组.我通过以下方式创建了这个数组:
I need to create two arrays. The first array is an array of all the keys from the object. I created this array by:
var labels = Object.keys(countries);
这很好用.我获得了一系列国家.现在,当我尝试从值创建数组时...
This works well. I obtain an array of countries. Now when I try to create an array from the values...
var labels = Object.values(countries);
我收到这个错误:Uncaught TypeError: Object.values is not a function JavaScript
我不知道我做错了什么.我在声明 labels
之前和之后 console.log countries
并且对象保持不变.如何正确使用 Object.values()
?
I don't know what I am doing wrong. I console.log countries
before and after I declare labels
and the object remains the same. How do I properly use Object.values()
?
.values
在许多浏览器中不受支持 - 您可以使用 .map
来获取所有的数组值:
.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];
});
参见 MDN 文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values 或官方文档:https://tc39.github.io/ecma262/#sec-object.values(感谢@evolutionxbox 的更正)
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)