获取关联数组键的列表 [英] Getting a list of associative array keys
问题描述
我在 JavaScript 中有一个关联数组:
I have an associative array in JavaScript:
var dictionary = {
"cats": [1,2,3,4,5],
"dogs": [6,7,8,9,10]
};
我如何获得这本字典的键?即,我想要
How do I get this dictionary's keys? I.e., I want
var keys = ["cats", "dogs"];
只是为了使术语正确 - JavaScript 中没有关联数组"这样的东西 - 从技术上讲,这只是一个 object
并且它是我们想要的对象键.
Just to get the terminology correct - there is no such thing as an 'associative array' in JavaScript - this is technically just an object
and it is the object keys we want.
推荐答案
您可以使用:Object.keys(obj)
示例:
var dictionary = {
"cats": [1, 2, 37, 38, 40, 32, 33, 35, 39, 36],
"dogs": [4, 5, 6, 3, 2]
};
// Get the keys
var keys = Object.keys(dictionary);
console.log(keys);
有关浏览器支持,请参阅下面的参考资料.它在 Firefox 4.20、Chrome 5 和 Internet Explorer 9 中受支持.Object.keys() 包含一个代码片段,如果您的浏览器不支持 Object.keys()
,您可以添加该代码片段.
See reference below for browser support. It is supported in Firefox 4.20, Chrome 5, and Internet Explorer 9. Object.keys() contains a code snippet that you can add if Object.keys()
is not supported in your browser.
这篇关于获取关联数组键的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!