【发布时间】:2020-02-11 00:03:40
【问题描述】:
我将一个 json 响应推送到一个数组中,但由于某种原因 数组长度的控制台日志即使通过也返回为 0 里面显然有一个物体。
let dogPool = [];
for (i=0; i<dogNumber; i++){
fetch('https://dog.ceo/api/breeds/image/random')
.then(response => response.json())
.then(responseJSON => dogPool.push(responseJSON))
.catch(error => alert('error! danger!'));
}
console.log(dogPool); //shows object
console.log(dogPool.length) // returns 0
控制台:
arrayAPI ran
[]0: {message: "https://images.dog.ceo/breeds/mastiff-english/2.jpg", status: "success"}1: {message: "https://images.dog.ceo/breeds/pembroke/n02113023_3474.jpg", status: "success"}2: {message: "https://images.dog.ceo/breeds/chihuahua/n02085620_326.jpg", status: "success"}length: 3__proto__: Array(0) //length 3, but proto array is 0?
0
【问题讨论】:
-
fetch是异步发生的,从技术上讲,push()代码 sn-p 发生在console.log()之后。
标签: arrays api asynchronous