JavaScript - 创建对象并使用变量作为属性名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4694652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:39:38  来源:igfitidea点击:

JavaScript - creating object and using variable for property name?

javascriptjqueryobjectproperties

提问by PruitIgoe

I am creating my own object:

我正在创建自己的对象:

gridObject = new Object();

I'm then using jquery to pull the contents of list item tags, which themselves are filled with

然后我使用 jquery 来提取列表项标签的内容,这些标签本身就充满了

tags that have specific class names:

具有特定类名的标签:

<li row="1"><p class="department" rowitem="department">Photography</p>...</li>

I'm pulling them using this code:

我正在使用此代码拉它们:

//make object from results
gridObject = new Object();

//get all the rows
var rowlist = $('li[row]');

for(var r=0; r<rowlist.length; r++) {

    //make gridObject row element here

    //get the row content
    var thisrow = $(rowlist[r]).html();

    //get all the p tags
    var rowitems = $(thisrow + 'p.[rowitem]');

    //get field name
    for(var ri=0; ri<rowitems.length; ri++) {
    if (r < 2) { //this is temporary just for testing
         var fieldname = $(rowitems[ri]).attr('rowitem');
         var fieldvalue = $(rowitems[ri]).html();
    }
    }

I'm getting hung up passing this into my object. Two questions. Can an object property be made with a variable name, like so

我在将它传递给我的对象时被挂断了。两个问题。可以使用变量名称创建对象属性吗,像这样

griObject.fieldname = fieldvalue;

and can the objects have parent/child relationships such as:

对象是否可以具有父/子关系,例如:

gridObject.r.fieldname = fieldvalue; 

in this case both r and fieldname would be variables. Or should I just be working associative arrays to achieve something similar?

在这种情况下, r 和 fieldname 都是变量。或者我应该只是使用关联数组来实现类似的功能?

This is in answer to a follow up question I posted below, "is there a print_r equivalent in javascript" - you can use iterator, a bit more typing but does the trick:

这是对我在下面发布的后续问题的回答,“javascript 中是否有 print_r 等效项”-您可以使用迭代器,输入更多内容,但可以解决问题:

//loop through search data
var it = Iterator(filteritems); 
for(var pair in it) { 
    console.log("key:" + pair[0] + ", value:" + pair[1] + "\n");
}

回答by Skilldrick

If you want to use a variable property name, use subscript syntax:

如果要使用变量属性名称,请使用下标语法:

var fieldname = 'test';

//These two lines are equivalent as long as fieldname is 'test':
gridObject[fieldname] = fieldvalue;
gridObject.test = fieldvalue