JavaScript-创建对象并使用变量作为属性名称? [英] JavaScript - creating object and using variable for property name?

查看:59
本文介绍了JavaScript-创建对象并使用变量作为属性名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建自己的对象:

I am creating my own object:

gridObject = new Object();

然后我使用jquery提取列表项标签的内容,列表项标签本身填充有具有特定类名的

标签:

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

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; 

在这种情况下,

r和fieldname都是变量.还是我应该在关联数组中实现相似的目的?

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

这是我在下面发布的后续问题的答案,"javascript中是否有等效的print_r"-您可以使用迭代器,键入更多一些,但是可以解决问题:

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:

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

推荐答案

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

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

这篇关于JavaScript-创建对象并使用变量作为属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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