This question already has answers here:
Dynamically access object property using variable

(16个答案)


7年前关闭。




我正在尝试解析Javascript中的JSON。 JSON被创建为ajax响应:
$.ajax(url, {
  dataType: "text",
  success: function(rawData, status, xhr) {
    var data;
    try {
      data = $.parseJSON(rawData);
      var counter = data.counter;
      for(var i=1; i<=counter; i++){
        //since the number of 'testPath' elements in the JSON depend on the 'counter' variable, I am parsing it in this way
        //counter has the correct integer value and loops runs fine
        var currCounter = 'testPath'+i ;
        alert(data.currCounter); // everything alerts as undefined
      }
    } catch(err) {
      alert(err);
    }
  },
  error: function(xhr, status, err) {
    alert(err);
  }
});

但是所有值都会将“未定义”警报为值(“计数器”给出正确的值除外),在 Firebug 中看到的实际字符串如下:
{"testPath1":"ab/csd/sasa", "testPath2":"asa/fdfd/ghfgfg", "testPath3":"ssdsd/sdsd/sds", "counter":3}

最佳答案

alert(data[currCounter]),这将起作用。

因为data.currCounter在对象中查找键“currCounter”,而不是通过currCounter的值。

例:

http://jsfiddle.net/bJeWm/1/

var myObj = { 'name':'dhruv','age':28 };
var theKey = 'age';
alert(myObj.theKey);  // undefined
alert(myObj[theKey]); // 28

10-04 11:31