如何列出JavaScript对象的属性?

本文翻译自:How to list the properties of a JavaScript object?

Say I create an object thus: 假设我创建了一个对象:

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

What is the best way to retrieve a list of the property names? 检索属性名称列表的最佳方法是什么? ie I would like to end up with some variable 'keys' such that: 即我想最终得到一些变量'键',这样:

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

#1楼

参考:https://stackoom.com/question/s76/如何列出JavaScript对象的属性


#2楼

This will work in most browsers, even in IE8 , and no libraries of any sort are required. 这适用于大多数浏览器,即使在IE8中也是如此,并且不需要任何类型的库。 var i is your key. var i是你的关键。

var myJSONObject =  {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; 
var keys=[];
for (var i in myJSONObject ) { keys.push(i); }
alert(keys);

#3楼

在支持js 1.8的浏览器下:

[i for(i in obj)]

#4楼

Could do it with jQuery as follows: 可以用jQuery做到如下:

var objectKeys = $.map(object, function(value, key) {
  return key;
});

#5楼

Mozilla has full implementation details on how to do it in a browser where it isn't supported, if that helps: Mozilla有关于如何在不支持的浏览器中执行此操作的完整实现详细信息 ,如果有帮助:

if (!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 (obj) {
      if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');

      var result = [];

      for (var prop in obj) {
        if (hasOwnProperty.call(obj, prop)) result.push(prop);
      }

      if (hasDontEnumBug) {
        for (var i=0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
        }
      }
      return result;
    };
  })();
}

You could include it however you'd like, but possibly in some kind of extensions.js file at the top of your script stack. 您可以根据需要包含它,但可能包含在脚本堆栈顶部的某种extensions.js文件中。


#6楼

I'm a huge fan of the dump function. 我是转储功能的忠实粉丝。

http://ajaxian.com/archives/javascript-variable-dump-in-coldfusion http://ajaxian.com/archives/javascript-variable-dump-in-coldfusion 替代文字

发布了0 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/105409415