0

我有几个objects从 ajax 调用返回的 json:

...
main: [{
 0: { // i'm showing only one... have severals
    IMGNAM0: "856f070054d378fa5681332095257c3c94d5f858.jpg"
    IMGNAM1: "68dfda9de984e914b7027c4a3cda51fb375dd828.jpg"
    IMGNAM2: "da0a1a3f68af208baca5eae23900548b40adfbef.jpg"
    IMGNAM3: "c8b540f8bdfe054e3c888e800b380dd60a4ac371.jpg"
    IMGNAM4: "565eb06485c51123786a88b8d5537c6b45add950.jpg"
    IMGPAT0: "./static/uploaded_images/1/"
    IMGPAT1: "./static/uploaded_images/1/"
    IMGPAT2: "./static/uploaded_images/1/"
    IMGPAT3: "./static/uploaded_images/1/"
    IMGPAT4: "./static/uploaded_images/1/"
 }
}]
...

所以,我需要动态获取这个 obj 名称,我用我正在尝试做的事情进行快速预览:

var mainlen = data.main.length-1; // get number of obj
for(var i = 0; i <= mainlen; i++){
   for(var j = 0; j <= 4; j++){ // examples to get all 4 obj names
        if(data.main[i].IMGNAM+j != null){
             // trying to get IMGNAM0 concatenate with j
             console.log(data.main[i].IMGNAM+j); 
             console.log(data.main[i].IMGPAT+j);
        }
   }
}

控制台向我显示not a number (NaN),完成这项工作的最佳方法是什么?

4

4 回答 4

1

而不是使用点来访问数据,使用.IMGNAM+j,使用[IMGNAM+j]

于 2013-03-08T12:14:29.363 回答
0

使用如下代码:

var mainlen = data.main.length-1; // get number of obj
for(var i = 0; i <= mainlen; i++){
   for(var j = 0; j <= 4; j++){ // examples to get all 4 obj names
        if(data.morrows[i].['IMGNAM'+j] != null){
             // trying to get IMGNAM0 concatenate with j
             console.log(data.main[i].['IMGNAM'+j]); 
             console.log(data.main[i].['IMGPAT'+j]);
        }
   }
}

这应该可以解决您的问题

于 2013-03-08T12:16:50.847 回答
0

你需要类似的东西:

 data.morrows[i]["IMGNAM" + j];
于 2013-03-08T12:17:11.047 回答
0

使用方括号来包装您的连接字符串:

if(data.main[i]['IMAGNAM'+j] != null){
于 2013-03-08T12:21:26.670 回答