3

我有从 JQuery .ajax 函数作为数组返回的数据。

现在该数组中的字段已命名并编号,即 part1、part2、part3 等。

我在下面有一些代码,我认为可能会遍历它,但它返回 NaN。

for (var a = 1; a <= 9; a++) {
newtext += '<div class="part">' + (exploded[0].part + a) + '</div>';
}

我无法让任何建议起作用,所以我这样做了。

var h = new Array();
h[1] = exploded[0].part_1;
h[2] = exploded[0].part_2;
h[3] = exploded[0].part_3;
h[4] = exploded[0].part_4;
h[5] = exploded[0].part_5;
h[6] = exploded[0].part_6;
h[7] = exploded[0].part_7;
h[8] = exploded[0].part_8;
h[9] = exploded[0].part_9;

我知道这有点啰嗦,但是当我处理多首歌曲时,我也可以使用数组键将它们全部循环。

4

4 回答 4

4

试试这种方式:

for (var a = 1; a <= 9; a++) {
    newtext += '<div class="part">' + (exploded[0]['part_' + a]) + '</div>';
}
于 2013-05-30T06:48:10.260 回答
0

您可以像这样迭代/循环数组的项目。您应该使用数组变量的属性“长度”,它告诉数组有多少项......

var myStringArray = ["part1", "part2", "part3"];
for (var i = 0; i < myStringArray.length; i++) {
    alert(myStringArray[i]);
    //Do something
}
于 2013-05-30T06:45:24.907 回答
0

确保您的数组爆炸有 10 个元素,因为数组的索引从零开始,因此对于 9 个元素,您可以编写这样的代码

   for (var a = 0; a <= exploded.length; a++) {
        newtext += '<div class="part">' + (exploded[a].part + a) + '</div>';
        }
    alert(newtext);

修改响应以动态访问属性 ---------

    var newtext='';
            alert('hi');
    var exploded= {"title":"Cornerstone","firstline":"","keysignature":"C","copyright":"","part_1":"sandeep","part_2":"","part_3":"","part_4":"","part_5":"","part_6":"","part_7":"","part_8":"","part_9":"","ref":"2"};
    var prop='';
    var newhtml='';

    for (var a = 1; a <= 9; a++) {
        prop='part_' + a;

        newhtml+='<div class="part">' + (exploded[prop]) + '</div>';
    }
    alert(newhtml);
于 2013-05-30T06:47:01.230 回答
0

以下情况如何:

var array=["part1", "part2", "part3"];
html=array.map(function(o){ return '<div class="part">'+o+'</div>' }).join("")
console.log(html);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2Fmap

于 2013-05-30T07:08:41.777 回答