【问题标题】:Array length returns zero数组长度返回零
【发布时间】: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


【解决方案1】:

在代码末尾试试这个:

setTimeout(function() {console.log(dogPool.length);},2000);

【讨论】:

    【解决方案2】:

    我将该函数设为异步函数,然后将 await 添加到 fetch

    async function arrayAPI(){
        console.log("arrayAPI ran");
    
        let dogPool = [];
        for (i=0; i<dogNumber; i++){
            await 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);
        console.log("length of dogpool: " + dogPool.length);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-28
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 2020-05-25
      • 2010-09-22
      相关资源
      最近更新 更多