如何找到对象的键? [英] How can I find the keys of an object?

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

问题描述

我在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)中有一个称为

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 the Mozilla site there is also a snippet 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天全站免登陆