【发布时间】:2018-11-05 07:47:58
【问题描述】:
这是我的代码
let loadInitialImages = ($) => {
let html = "";
let images = new Array();
const APIURL = "https://api.shutterstock.com/v2/images/licenses";
const request = async() => {
const response = await fetch(APIURL, { headers: auth_header() } );
const json = await response.json();
json.data.map((v) => images.push(v.image.id)); //this is where the problem is
}
request();
// I can see the contents of the array when I log it.
console.log(images);
// But I can't see any elements when logging this way:
images.map((id) => console.log(id));
}
这里一切正常,但问题是当我将元素推入数组时,数组括号[] 超出了以下是我数组的屏幕截图:
我无法在此处循环遍历数组。
请参见此处的数组大括号。元素似乎在 [1, 2, 3] 内部
【问题讨论】:
-
“走出数组大括号”到底是什么意思?你的数组截图对我来说很好。
-
images = json.data.map((v) => v.image.id);
-
您没有等待请求完成。你需要先
await request();console.log(images); -
当您调用
console.log(images)时,images为空,然后request填充它 - 这就是您可以展开它并查看 ID 的原因 -
@adiga 这正是我的想法,直到我将它与通常的数组进行比较。请参阅更新后的问题。
标签: javascript arrays google-chrome async-await console.log