Javascript获取对象密钥名称 [英] Javascript get object key name

查看:99
本文介绍了Javascript获取对象密钥名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获得以下关键名称?例如,我想要button1和button2?

How would I get the key name for the follow? E.g I want "button1" and "button2"?

var buttons = {
    button1: {
        text: 'Close',
        onclick: function(){

        }
    },
    button2: {
        text: 'Close2',
        onclick: function(){

        }
    }
}

var i;
for(i in buttons){
    if(buttons.hasOwnProperty(i)){
        alert(buttons[i].text);
    }
} 

我尝试使用 .push ()虽然这不起作用。

I tried using .push() although this didn't work.

推荐答案

如果您稍微修改一下这个措辞,可能会更好理解:

This might be better understood if you modified the wording up a bit:

var buttons = {
  foo: 'bar',
  fiz: 'buz'
};

for ( property in buttons ) {
  console.log( property ); // Outputs: foo, fiz or fiz, foo
}

请注意,你'重复迭代对象的属性,使用属性作为每个后续周期中每个属性的引用。

Note here that you're iterating over the properties of the object, using property as a reference to each during each subsequent cycle.

< a href =http://msdn.microsoft.com/en-us/library/55wb2d34%28v=vs.94%29.aspx\"rel =noreferrer> MSDN 说 for([object | array]中的变量)以下内容:


在每次循环迭代之前,变量被赋予对象的下一个属性名称或数组的下一个元素索引。然后,您可以在循环内的任何语句中使用它来引用对象的属性或数组的元素。

Before each iteration of a loop, variable is assigned the next property name of object or the next element index of array. You can then use it in any of the statements inside the loop to reference the property of object or the element of array.

另请注意对象的属性顺序不是常量,并且可以更改,与数组的索引顺序不同。这可能会派上用场。

Note also that the property order of an object is not constant, and can change, unlike the index order of an array. That might come in handy.

这篇关于Javascript获取对象密钥名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆