1

好的第一件事json结构

[{
    "type": "button",
    "name": "Off",
    "tabname": "1",
    "image_file": "path\\Off.gif"
  }, {
    "type": "button",
    "name": "Off1",
    "tabname": "2",
    "image_file": "path\\Off1.gif",
    "image_file_1": "path\\On1.gif"
  }, {
    "type": "button",
    "name": "Off2",
    "tabname": "3",
    "image_file": "path\\Off2.gif",
    "image_file_1": "path\\On2.gif",
    "image_file_2": "path\\half.gif"
  }
]

image_file 字段可以有多个条目(即 image_file、image_file_1、image_file_2 等),我如何在循环中动态访问它?

当前不工作的代码(只是相关的东西)

$.each(data, function (i, item) {
  var images = [];
  imageIndex = 1;
  continueLoop = true;
  while(continueLoop) {
    if(imageIndex == 1) {
      images.push(data[i].image_file);
    }
    else {
      var testVal = 'image_file_' + imageIndex;
      alert(data[i][testVal]);
      if(data[i][testVal] === undefined) {
        continueLoop = false;
      }
      else {
        images.push(data[i][testVal]);

      }
    }
    imageIndex++;
  }
});

第一次迭代工作正常(if (imageIndex == 1) 即位),但else我为测试值而输入的子句 alert 总是返回 undefined

任何帮助将不胜感激

4

3 回答 3

2

You're skipping image_file_1, and going directly from image_file to image_file_2

Try starting imageIndex at 0, and mapping 0 to image_file.

imageIndex = 0;
continueLoop = true;
while(continueLoop) {
  if(imageIndex == 0) {
    images.push(data[i].image_file);
  }
  // rest of your code unchanged
于 2013-06-08T02:19:06.927 回答
2

据我了解您的代码,您将获得所有image_file属性,即使是带有数字的属性。你可以很容易地做到这一点

var images = [];

//iterate through the array
$.each(data, function (i, item) {

  //iterate through each property
  $.each(item, function (key, value) {

    //if the property starts with image_file, push into the array
    if (key.indexOf('image_file') === 0) images.push(value);
  });
});

console.log(images); // ["path\\Off.gif","path\\Off1.gif","path\\On1.gif","path\\Off2.gif","path\\On2.gif","path\\half.gif"]
于 2013-06-08T02:21:16.360 回答
0

在这种情况下,最好的选择是使 image_files 成为 JSON 中的数组。

[{
   ...
  }, {
    "type": "button",
    "name": "Off2",
    "tabname": "3",
    "image_files": ["path\\Off2.gif", "path\\On2.gif","path\\half.gif"]
  }
]

然后你可以优雅地迭代那些。

但是由于我们都知道必须使用其他人的 JSON 的痛苦,所以我提取这些数据的方式如下:

images = []
$.each(data, function(i, item) {
    imageIndex = 0
    while ( true ) {
        image = item["image_file" + ( imageIndex === 0 ? "" : "_" + imageIndex )]
        if ( typeof image === 'undefined' ) {
            break
        }
        images.push(image)
        imageIndex += 1
    }
})
于 2013-06-08T02:57:53.430 回答