javascript在读取JSON文件后无法迭代数组
javascript can not iterate array after reading JSON file
我是javascript新手。我在读取简单的json文件时遇到问题。这是示例代码。
function readJson() {
$.getJSON('./resources/json/comments_type.json', function(data) {
$.each(data, function(index, comment) {
tempList.push(comment);
});
});
for(var i = 0 ; i<tempList.length;i++)
{
console.log(tempList[i].text);
}
}
在这里,我试图在读取JSON文件后迭代tempList数组。但是console.log没有显示任何内容。但如果我尝试console.log(tempList)
,它会起作用。tempList
是一个全局变量。我正在从另一个函数调用readJson
函数。JSON文件保存在此处JSON文件
由于$.getJSON是异步的,在实际获取任何数据之前,您似乎正在运行for循环。因此,请尝试将迭代器循环移动到$.getJSON回调。
function readJson() {
$.getJSON('./resources/json/comments_type.json', function(data) {
$.each(data, function(index, comment) {
tempList.push(comment);
});
//Here you should have the list
for(var i = 0 ; i<tempList.length;i++)
{
console.log(tempList[i].text);
}
});
}
readJSON函数。这意味着当您已经开始console.log tempList的内容时,它正在从url(在另一个线程中)加载JSON。下载后一定要阅读临时列表。这通常是通过回调完成的。或者您可以使这个请求同步(但这是错误的方法)。
function readJson() {
$.getJSON('./resources/json/comments_type.json', function(data) {
$.each(data, function(index, comment) {
tempList.push(comment);
});
for(var i = 0 ; i<tempList.length;i++)
{
console.log(tempList[i].text);
}
});
}
试试这个方法。你应该得到打印好的清单。您也可以将回调传递给readJson函数:
function readJson(callback) {
$.getJSON('./resources/json/comments_type.json', function(data) {
$.each(data, function(index, comment) {
tempList.push(comment);
});
callback();
});
}
然后在代码的其他地方:
readJson(function(){
for(var i = 0 ; i<tempList.length;i++)
{
console.log(tempList[i].text);
}
});
相关文章:
- 如何在DataTables 2.1中迭代对象数组
- 是否“;对于的“;循环迭代遵循JavaScript中的数组顺序
- 如何在Jquery中迭代JSON数组
- 为什么数组在对象内部迭代对象时存储重复值
- 迭代和修改Firebase数组会导致未定义
- 在对象上迭代以验证它是否's键存在于数组中
- 在JSON数组中进行迭代,并为其元素设置样式
- 我需要迭代一个JSON数组——不知道如何做到——已经搜索过了,但仍然可以'我一点也不知道
- JavaScript:如何在迭代过程中修改数组中的值
- 使用Ruby数组使用JS在视图中进行迭代和显示
- 使用javascript在数组中迭代和映射JSON
- 在数组中迭代时的JS循环位置
- 在可变长度d3的多维数组上迭代
- MVC:使用Web窗体视图引擎在javascript中迭代Viewbag数组
- 如何通过迭代对象数组来删除某些项目
- 如何在 JavaScript 中动态地编写可迭代的函数数组
- 使用节点在 JSON 数组中搜索项目(最好不迭代)
- 使用 promises/dedelay 异步迭代一组文件
- 不能让.offset()方法在迭代一组列表项时工作
- 迭代2个数组并找到匹配,但需要相同的索引