JavaScript-使用变量来引用属性名称? [英] JavaScript - Using a variable to refer to a property name?
问题描述
我正在创建自己的对象:
I am creating my own object:
gridObject = new Object();
然后我使用jquery提取列表项标签的内容,列表项标签本身填充有具有特定类名的
标签:
I am 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 am 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();
}
}
我挂断了电话,将其传递到我的对象中.两个问题.可以使用变量名来制作对象属性吗?
Ia 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屋!