获取关联数组键列表 [英] Getting a list of associative array keys

查看:109
本文介绍了获取关联数组键列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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"];






编辑7年后:只是为了得到术语正确 - 在Javascript中没有关联数组这样的东西 - 这在技术上只是一个对象,它是我们想要的对象键。


Edit 7 years later: 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,IE9支持它。如果您的浏览器不支持 Object.keys(),则下面的链接包含您可以添加的代码段。

See reference below for browser support. It is supported in Firefox 4.20, Chrome 5, IE9. The link below contains a code snippet that you can add if Object.keys() is not supported in your browser.

https://developer.mozilla.org/en/JavaScript/参考/ Global_Objects /对象/键

这篇关于获取关联数组键列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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