如何枚举JavaScript对象的属性?[重复]

如何枚举JavaScript对象的属性?

我实际上想列出所有已定义的变量及其值,但是我了解到定义一个变量实际上会创建window对象的属性。

小卤蛋Stafan2020/03/11 15:31:59

If you are using the Underscore.js library, you can use function keys:

_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]
小小Gil2020/03/11 15:31:59

You can use the for of loop.

If you want an array use:

Object.keys(object1)

Ref. Object.keys()

西门十三LEY2020/03/11 15:31:59

I found it... for (property in object) { // do stuff } will list all the properties, and therefore all the globally declared variables on the window object..

村村Tony2020/03/11 15:31:59

在现代浏览器(ECMAScript 5)中,要获取所有可枚举的属性,您可以执行以下操作:

Object.keys(obj) (检查链接以获得片段,以在较旧的浏览器上向后兼容)

或也获得不可枚举的属性:

Object.getOwnPropertyNames(obj)

检查ECMAScript 5兼容性表

附加信息: 什么是可枚举属性?

Stafan小宇宙2020/03/11 15:31:59

我认为举个例子令我吃惊:

var myObject = { name: "Cody", status: "Surprised" };
for (var propertyName in myObject) {
  document.writeln( propertyName + " : " + myObject[propertyName] );
}

但令我惊讶的是,输出是

name : Cody
status : Surprised
forEach : function (obj, callback) {
    for (prop in obj) {
        if (obj.hasOwnProperty(prop) && typeof obj[prop] !== "function") {
            callback(prop);
        }
    }
}

为什么?页面上的另一个脚本扩展了Object原型:

Object.prototype.forEach = function (obj, callback) {
  for ( prop in obj ) {
    if ( obj.hasOwnProperty( prop ) && typeof obj[prop] !== "function" ) {
      callback( prop );
    }
  }
};
2020/03/11 15:31:59

已经多次提出的标准方法是:

for (var name in myObject) {
  alert(name);
}

但是,Internet Explorer 6、7和8在JavaScript解释器中存在一个错误,该错误导致未枚举某些键。如果运行此代码:

var obj = { toString: 12};
for (var name in obj) {
  alert(name);
}

如果将在除IE之外的所有浏览器中警告“ 12”。IE只会忽略此键。受影响的键值为:

  • isPrototypeOf
  • hasOwnProperty
  • toLocaleString
  • toString
  • valueOf

为了在IE中真正安全,您必须使用以下方法:

for (var key in myObject) {
  alert(key);
}

var shadowedKeys = [
  "isPrototypeOf",
  "hasOwnProperty",
  "toLocaleString",
  "toString",
  "valueOf"
];
for (var i=0, a=shadowedKeys, l=a.length; i<l; i++) {
  if map.hasOwnProperty(a[i])) {
    alert(a[i]);
  }
}

好消息是EcmaScript 5定义了该Object.keys(myObject)函数,该函数以数组的形式返回对象的键,并且某些浏览器(例如Safari 4)已经实现了该功能。

十三村村蛋蛋2020/03/11 15:31:59
for (prop in obj) {
    alert(prop + ' = ' + obj[prop]);
}
伽罗GreenNear2020/03/11 15:31:59

简单的JavaScript代码:

for(var propertyName in myObject) {
   // propertyName is what you want.
   // You can get the value like this: myObject[propertyName]
}

jQuery的:

jQuery.each(obj, function(key, value) {
   // key is what you want.
   // The value is in: value
});