假设我这样创建一个对象:

var myObject =
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};

检索属性名列表的最佳方法是什么?例如,我想以一些变量“键”结束,这样:

keys == ["ircEvent", "method", "regex"]

当前回答

正如Sam Dutton回答的那样,ECMAScript第5版引入了一种新的方法。Object.keys()将做你想做的事情,并在Firefox 4, Chrome 6, Safari 5和IE 9中得到支持。

您也可以很容易地在不支持该方法的浏览器中实现该方法。然而,有些实现并不完全与Internet Explorer兼容。这里有一个更兼容的解决方案:

Object.keys = Object.keys || (function () {
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
        DontEnums = [ 
            'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',
            'isPrototypeOf', 'propertyIsEnumerable', 'constructor'
        ],
        DontEnumsLength = DontEnums.length;
        
    return function (o) {
        if (typeof o != "object" && typeof o != "function" || o === null)
            throw new TypeError("Object.keys called on a non-object");
    
        var result = [];
        for (var name in o) {
            if (hasOwnProperty.call(o, name))
                result.push(name);
        }
    
        if (hasDontEnumBug) {
            for (var i = 0; i < DontEnumsLength; i++) {
                if (hasOwnProperty.call(o, DontEnums[i]))
                    result.push(DontEnums[i]);
            }   
        }
    
        return result;
    };
})();

请注意,当前接受的答案不包括检查hasOwnProperty(),并将返回通过原型链继承的属性。它也没有解释Internet Explorer中著名的DontEnum错误,即原型链上的不可枚举属性会导致本地声明的具有相同名称的属性继承其DontEnum属性。

实现Object.keys()将为您提供更健壮的解决方案。

编辑:在最近与Prototype的知名贡献者kangax讨论之后,我基于他Object.forIn()函数的代码实现了DontEnum错误的解决方案。

其他回答

这里有很多答案…这是我的意见。

我需要一些东西来打印出所有的JSON属性,甚至是带有子对象或数组的属性(包括父名称)。

对于这个JSON:

mylittleJson = {
  "one": "blah",
  "two": {
      "twoone": "",
      "twotwo": "",
      "twothree": ['blah', 'blah']
  },
  "three": ""
}

它会打印这个:

.one
.two.twoone
.two.twotwo
.two.twothree
.three

这是函数

function listatts(parent, currentJson){ var attList = [] if (typeof currentJson !== 'object' || currentJson == undefined || currentJson.length > 0) { return } for(var attributename in currentJson){ if (Object.prototype.hasOwnProperty.call(currentJson, attributename)) { childAtts = listatts(parent + "." + attributename, currentJson[attributename]) if (childAtts != undefined && childAtts.length > 0) attList = [...attList, ...childAtts] else attList.push(parent + "." + attributename) } } return attList } mylittleJson = { "one": "blah", "two": { "twoone": "", "twotwo": "", "twothree": ['blah', 'blah'] }, "three": "" } console.log(listatts("", mylittleJson));

希望这也能有所帮助。

我是转储功能的超级粉丝。

ajax»JavaScript变量转储在Coldfusion

下载转储功能

IE不支持(i in obj)原生属性。这是我能找到的所有道具的清单。

似乎stackoverflow做了一些愚蠢的过滤。

该列表可在这个谷歌组帖子的底部:- https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0

在支持js 1.8的浏览器下:

[i for(i in obj)]

注意Object。Firefox 4、Chrome 6、Safari 5、IE 9及以上版本均支持key和其他ECMAScript 5方法。

例如:

var o = {"foo": 1, "bar": 2}; 
alert(Object.keys(o));

ECMAScript 5兼容性表

新方法描述