未捕获的 TypeError:Object.values 不是函数 JavaScript [英] Uncaught TypeError: Object.values is not a function JavaScript

查看:74
本文介绍了未捕获的 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)

这篇关于未捕获的 TypeError:Object.values 不是函数 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆