JavaScript - 使用变量来引用属性名称?
我正在创建自己的对象:
gridObject = new Object();
然后使用 jquery 来提取列表项标签的内容,这些标签本身充满了
具有特定类名的标签:
<li row="1"><p class="department" rowitem="department">Photography</p>...</li>
我使用以下代码来提取它们:
//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();
}
}
我挂断了将其传递到我的目的。两个问题。对象属性是否可以使用变量名来创建,就像这样
griObject.fieldname = fieldvalue;
,对象是否可以具有父/子关系,例如:
gridObject.r.fieldname = fieldvalue;
在这种情况下,r 和 fieldname 都是变量。或者我应该只是使用关联数组来实现类似的目标?
这是对我在下面发布的后续问题的回答:“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");
}
I am creating my own object:
gridObject = new Object();
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;
in this case both r and fieldname would be variables. Or should I just be working associative arrays to achieve something similar?
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");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果要使用变量属性名称,请使用下标语法:
If you want to use a variable property name, use subscript syntax: