JavaScript函数push问题

3

i've following JS function.

responseData:function(resp){
    this.jsondata = eval('(' + resp + ')');
    this.propList = [];
    for (var i = 0;i<this.jsondata.length;i++) {
        for (obj in this.jsondata[i]) {
            alert(obj); //shows the property name of obj
            this.propList.push({
                obj : this.jsondata[i][obj] //insert only simple obj string
            });
        }
    }
    return this.propList;
}

我希望将属性名称和值插入到我的propList中,但是这个函数插入的只是一个字符串'obj',而不是属性名称。我做错了什么?
问候 Stefan
1个回答

4

将循环改为:

    for (obj in this.jsondata[i]) {
        alert(obj); //shows the property name of obj
        var item = {};
        item[obj] = this.jsondata[i][obj];
        this.propList.push(item);
    }

当您使用对象字面量创建对象时,属性名称不会作为变量进行评估。如果要使用变量的当前值指定对象属性的名称,则必须使用obj[variable]格式。这将在obj中创建一个属性,其名称将与variable的当前值相同。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接