使用Javascript .push方法推入数组后无法使用JSON数据

时间:2019-03-11 03:54:54

标签: javascript jquery arrays json array-push

将其存储在getJSON之外的变量中后,我无法从数组中检索值。

我的 JSON响应是:

[
    {
        "Book_ID": "1",
        "Book_Name": "Computer Architecture",
        "Category": "Computers",
        "Price": "125.60"
    },
    {
        "Book_ID": "2",
        "Book_Name": "Asp.Net 4 Blue Book",
        "Category": "Programming",
        "Price": "56.00"
    },
    {
        "Book_ID": "3",
        "Book_Name": "Popular Science",
        "Category": "Science",
        "Price": "210.40"
    }
]

使用jQuery $ .getJson函数:

  var booksList = [];
  $.getJSON( "books.json", function( data ) {
    $.each(data, function (index, value) {
     booksList.push(value);
    });
  });

当我尝试获取BOOK ID时,

console.log(booksList[0].BOOK_ID);

我收到以下错误

  

未捕获的TypeError:无法读取未定义的属性'Book_ID'

但是当我记录整个阵列时,

console.log(booksList);

I see this response in the console:

1 个答案:

答案 0 :(得分:0)

var booksList = [];
$.getJSON( "books.json", function( data ) {
  $.each(data, function (index, value) {
   booksList.push(value);
  });
});

$.getJSON()立即返回,$.each()也立即返回,而函数中的代码仍在单独的线程中执行。之后的代码会立即执行,因此当您尝试从列表中获取数据时,列表不会更新,并且列表为空,因此会出现错误

var booksList = [];
$.getJSON( "books.json", function( data ) {
  $.each(data, function (index, value) {
   booksList.push(value);
   console.log(booksList[0].Book_ID);
  });
});
console.log("hi");

将在首先打印"hi"时显示更新的列表。