0

根据我之前的帖子,我正在尝试从名为winners.json 的JSon 文件中获取名称,其格式类似于:

    {"driver":[
      {
        "Year":1984,
        "Name":"Name1",
      },
      {
        "Year":1985,
        "Name":"Name2",
      },
    [etc...]
    ]}

在 JavaScript 文件中,我从滑块中获取一个值,这将是我要在 JSon 文件中搜索的年份。使用控制台,该值的类型是“数字”。但是当我在整个 JSon 中搜索年份时,控制台说 Json 中的“年份”字段是未定义的值,所以我无法获得“名称”字段:

    var len=winners.winner.length;
    console.info(len + " values in JSon");
    for (var i=0; i < len; i++) {
        console.info("Reading line " + i + " Type: " + typeof(winners.winner[i].Year) + " Year: " + winners.winner[i].Year);
        [more code...]
    }

var len 被正确读取。我试着做一个铸造号码(winners.winner[i].Year),但我得到了 NaN 值。

谢谢。

4

1 回答 1

0

Assuming your code looks similar to the following:

var jsondata = '{"winner":[ { "Year":1984, "Name":"Name1" }, { "Year":1985, "Name":"Name2" }]';

console.info(jsondata.length)     

for (var i=0; i < len; i++) {
   console.info("Reading line " + i + " Type: " + typeof(jsondata.winner[i].Year) + " Year: " +
   winners.winner[i].Year);
}

Then it is correct that the len variable will return a positive integer, this will not however be the number of array elements in your JSON but instead the number of characters in the string. As mentioned by @Nirk, a call to JSON.parse(jsondata); is needed to turn the JSON string into a JavaScript object.

于 2013-06-23T09:30:37.497 回答