如何找到哈希的键? [英] How to find keys of a hash?

查看:198
本文介绍了如何找到哈希的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在javascript对象中加倍作为哈希但我无法找到内置函数来获取密钥

I know in javascript Objects double as hashes but i have been unable to find a built in function to get the keys

var h = {a:'b',c:'d'};

我想要类似

var k = h.keys() ; // k = ['a','c'];

自己编写一个函数来迭代项目并将键添加到一个数组是很简单的我回来了,但有没有一种标准的清洁方法呢?

It is simple to write a function myself to iterate over the items and add the keys to an array that I return, but is there a standard cleaner way to do that?

我一直认为它必须是一个简单的内置功能,我错过了但我找不到它!

I keep feeling it must be a simple built in function that I missed but I can't find it!

推荐答案

现代javascript(ECMAScript 5)中有一个名为 Object.keys

There is function in modern javascript (ECMAScript 5) called Object.keys performing this operation:

var obj = { "a" : 1, "b" : 2, "c" : 3};
alert(Object.keys(obj)); // will output ["a", "b", "c"]

兼容性详细信息可以是找到此处

Compatibility details can be found here.

Mozilla上网站还有一个向后兼容的剪切:

On Mozilla site there is also a snipped for backward compatibility:

if(!Object.keys) Object.keys = function(o){
   if (o !== Object(o))
      throw new TypeError('Object.keys called on non-object');
   var ret=[],p;
   for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
   return ret;
}

这篇关于如何找到哈希的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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