我从ajax调用返回了几个json objects
:
...
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)
,
使这项工作的最佳方法是什么?
答案 0 :(得分:1)
使用.IMGNAM+j
,而不是[IMGNAM+j]
使用点来访问数据。
答案 1 :(得分: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]);
}
}
}
这应该可以解决你的问题
答案 2 :(得分:0)
您需要以下内容:
data.morrows[i]["IMGNAM" + j];
答案 3 :(得分:0)
使用方括号来包装连接字符串:
if(data.main[i]['IMAGNAM'+j] != null){