如果我不知道名称,如何访问 javascript 对象的属性?

发布于 2024-07-15 10:50:51 字数 385 浏览 4 评论 0原文

假设你有一个像这样的 javascript 对象:

var data = { foo: 'bar', baz: 'quux' };

你可以通过属性名称访问属性:

var foo = data.foo;
var baz = data["baz"];

但是如果你不知道属性的名称,是否可以获得这些值? 这些属性的无序性质是否导致无法区分它们?

就我而言,我特别考虑这样一种情况:函数需要接受一系列名称-值对,但属性的名称可能会发生变化。

到目前为止,我对如何做到这一点的想法是将属性名称与数据一起传递给函数,但这感觉像是一个黑客。 如果可能的话,我更愿意通过内省来做到这一点。

Say you have a javascript object like this:

var data = { foo: 'bar', baz: 'quux' };

You can access the properties by the property name:

var foo = data.foo;
var baz = data["baz"];

But is it possible to get these values if you don't know the name of the properties? Does the unordered nature of these properties make it impossible to tell them apart?

In my case I'm thinking specifically of a situation where a function needs to accept a series of name-value pairs, but the names of the properties may change.

My thoughts on how to do this so far is to pass the names of the properties to the function along with the data, but this feels like a hack. I would prefer to do this with introspection if possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

锦欢 2024-07-22 10:50:51

您可以像这样循环遍历键:

for (var key in data) {
  console.log(key);
}

这会记录“名称”和“值”。

如果您有更复杂的对象类型(不仅仅是像原始问题中那样的普通散列对象),您将只想循环属于对象本身的键,而不是对象的 原型

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    console.log(key);
  }
}

正如您所指出的,不保证密钥按任何特定顺序排列。 请注意这与以下示例有何不同:

for each (var value in data) {
  console.log(value);
}

此示例循环遍历值,因此它将记录 Property Name0。 注意:每个 语法大多仅在 Firefox 中受支持,而在其他浏览器中则不受支持。

如果您的目标浏览器支持 ES5,或者您的网站包含 es5-shim.js (推荐),您还可以使用 Object.keys

var data = { Name: 'Property Name', Value: '0' };
console.log(Object.keys(data)); // => ["Name", "Value"]

并使用 Array.prototype.forEach

Object.keys(data).forEach(function (key) {
  console.log(data[key]);
});
// => Logs "Property Name", 0

You can loop through keys like this:

for (var key in data) {
  console.log(key);
}

This logs "Name" and "Value".

If you have a more complex object type (not just a plain hash-like object, as in the original question), you'll want to only loop through keys that belong to the object itself, as opposed to keys on the object's prototype:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    console.log(key);
  }
}

As you noted, keys are not guaranteed to be in any particular order. Note how this differs from the following:

for each (var value in data) {
  console.log(value);
}

This example loops through values, so it would log Property Name and 0. N.B.: The for each syntax is mostly only supported in Firefox, but not in other browsers.

If your target browsers support ES5, or your site includes es5-shim.js (recommended), you can also use Object.keys:

var data = { Name: 'Property Name', Value: '0' };
console.log(Object.keys(data)); // => ["Name", "Value"]

and loop with Array.prototype.forEach:

Object.keys(data).forEach(function (key) {
  console.log(data[key]);
});
// => Logs "Property Name", 0
听风念你 2024-07-22 10:50:51

旧版本的 JavaScript (< ES5) 需要使用 for..in 循环:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    // do something with key
  }
}

ES5 引入了 Object.keysArray#forEach 这使得这变得更容易一些:

var data = { foo: 'bar', baz: 'quux' };

Object.keys(data); // ['foo', 'baz']
Object.keys(data).map(function(key){ return data[key] }) // ['bar', 'quux']
Object.keys(data).forEach(function (key) {
  // do something with data[key]
});

ES2017< /a> 引入 Object.valuesObject.entries

Object.values(data) // ['bar', 'quux']
Object.entries(data) // [['foo', 'bar'], ['baz', 'quux']]

Old versions of JavaScript (< ES5) require using a for..in loop:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    // do something with key
  }
}

ES5 introduces Object.keys and Array#forEach which makes this a little easier:

var data = { foo: 'bar', baz: 'quux' };

Object.keys(data); // ['foo', 'baz']
Object.keys(data).map(function(key){ return data[key] }) // ['bar', 'quux']
Object.keys(data).forEach(function (key) {
  // do something with data[key]
});

ES2017 introduces Object.values and Object.entries.

Object.values(data) // ['bar', 'quux']
Object.entries(data) // [['foo', 'bar'], ['baz', 'quux']]
无语# 2024-07-22 10:50:51
for(var property in data) {
    alert(property);
}
for(var property in data) {
    alert(property);
}
一桥轻雨一伞开 2024-07-22 10:50:51

您经常需要检查对象实例的特定属性,
没有它的所有共享原型方法和属性:

 Obj.prototype.toString= function(){
        var A= [];
        for(var p in this){
            if(this.hasOwnProperty(p)){
                A[A.length]= p+'='+this[p];
            }
        }

    return A.join(', ');
}

You often will want to examine the particular properties of an instance of an object,
without all of it's shared prototype methods and properties:

 Obj.prototype.toString= function(){
        var A= [];
        for(var p in this){
            if(this.hasOwnProperty(p)){
                A[A.length]= p+'='+this[p];
            }
        }

    return A.join(', ');
}
一个人的旅程 2024-07-22 10:50:51
function getDetailedObject(inputObject) {
    var detailedObject = {}, properties;

    do {
        properties = Object.getOwnPropertyNames( inputObject );
        for (var o in properties) {
            detailedObject[properties[o]] = inputObject[properties[o]];
        }
    } while ( inputObject = Object.getPrototypeOf( inputObject ) );

    return detailedObject;
}

这将获取新对象中的所有属性及其值(继承的或拥有的,可枚举的或不可枚举的)。 原始对象未受影响。 现在可以使用以下方式遍历新对象

var obj = { 'b': '4' }; //example object
var detailedObject = getDetailedObject(obj);
for(var o in detailedObject) {
    console.log('key: ' + o + '   value: ' + detailedObject[o]);
}
function getDetailedObject(inputObject) {
    var detailedObject = {}, properties;

    do {
        properties = Object.getOwnPropertyNames( inputObject );
        for (var o in properties) {
            detailedObject[properties[o]] = inputObject[properties[o]];
        }
    } while ( inputObject = Object.getPrototypeOf( inputObject ) );

    return detailedObject;
}

This will get all properties and their values (inherited or own, enumerable or not) in a new object. original object is untouched. Now new object can be traversed using

var obj = { 'b': '4' }; //example object
var detailedObject = getDetailedObject(obj);
for(var o in detailedObject) {
    console.log('key: ' + o + '   value: ' + detailedObject[o]);
}
意中人 2024-07-22 10:50:51

您可以使用 Object.keys(),“它返回一个给定对象自己的可枚举属性名称的数组,其顺序与我们使用普通循环得到的顺序相同。”

您可以使用任何对象来代替 stats

var stats = {
  a: 3,
  b: 6,
  d: 7,
  erijgolekngo: 35
}
/*  this is the answer here  */
for (var key in Object.keys(stats)) {
  var t = Object.keys(stats)[key];
  console.log(t + " value =: " + stats[t]);
}

You can use Object.keys(), "which returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop."

You can use any object in place of stats:

var stats = {
  a: 3,
  b: 6,
  d: 7,
  erijgolekngo: 35
}
/*  this is the answer here  */
for (var key in Object.keys(stats)) {
  var t = Object.keys(stats)[key];
  console.log(t + " value =: " + stats[t]);
}

凉墨 2024-07-22 10:50:51
var obj = {
 a: [1, 3, 4],
 b: 2,
 c: ['hi', 'there']
 }
for(let r in obj){  //for in loop iterates all properties in an object
 console.log(r) ;  //print all properties in sequence
 console.log(obj[r]);//print all properties values
}
var obj = {
 a: [1, 3, 4],
 b: 2,
 c: ['hi', 'there']
 }
for(let r in obj){  //for in loop iterates all properties in an object
 console.log(r) ;  //print all properties in sequence
 console.log(obj[r]);//print all properties values
}
薄荷→糖丶微凉 2024-07-22 10:50:51
var attr, object_information='';

for(attr in object){

      //Get names and values of propertys with style (name : value)
      object_information += attr + ' : ' + object[attr] + '\n'; 

   }


alert(object_information); //Show all Object
var attr, object_information='';

for(attr in object){

      //Get names and values of propertys with style (name : value)
      object_information += attr + ' : ' + object[attr] + '\n'; 

   }


alert(object_information); //Show all Object
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文