【问题标题】:different representation of arrays in chrome consolechrome控制台中数组的不同表示
【发布时间】: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


【解决方案1】:

由于您的request 函数是async,您需要将其结果视为Promise

这也是您在 chrome 控制台中看到它的表示方式不同的原因。打印一个空数组,但控制台中的引用会动态更新,因此您仍然可以展开它并查看内容。

如果你想静态记录数组的内容,你可以使用JSON.stringify 之类的东西来打印它。这将打印记录时数组的确切状态的字符串表示形式。

// You will need to check the output in the browser console.
// Your code could be reduced to this:
const a = []; 
setTimeout(() => a.push(1, 2), 100); 
console.log('a:', a);

// A filled array logs differently:
const b = [1, 2]; 
console.log('b:', b);

// Stringify gives you a fixed state:
const c = []; 
setTimeout(() => c.push(1, 2), 100);
console.log('c:', JSON.stringify(c));

关于您的代码,除了等待request(),如果您使用的是map,您应该利用of how it works。例如,您可以使用它来生成整个数组,而无需使用 push。如果您仍想使用您的数组和push(),您应该使用json.data.forEach 而不是json.data.map,因为它不会复制数组。

// Making your function `async` so you can `await` for the `request()`
let loadInitialImages = async ($) => {
  let html = "";
  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();
    // Array.map will return a new array with the results of applying 
    // the given function to the original array, you can use that as 
    // an easy way to return your desired array.
    return json.data.map((v) => v.image.id); 
  }

  // Since request() is async, you need to wait for it to complete.
  const images = await request();
  // Array.forEach lets you iterate over an array without generating a
  // copy. If you use map here, you would be making an unneeded copy 
  // of your images array.
  images.forEach(i => console.log(i));
}

【讨论】:

  • 不,我不与表示混淆。这里的问题是我无法遍历数组。
  • 已更新以解决我认为的实际问题:chrome 对这个数组做了什么?
  • 没错。这是我的问题。人们甚至在不了解实际问题的情况下就对问题投反对票
【解决方案2】:

下面的片段演示了您的问题(您的案例是arr1,您想要arr2)。
如果loadInitialImages 不能是async,请使用arr3 场景。

async function main(){
let arr1 = [], arr2 = [], arr3 = [];

const getArray = ()=> (new Promise(resolve=>setTimeout(()=>{resolve([1,2,3])},1000)))



async function request(arr, number){
  var result = await getArray();
  result.forEach((el)=>(arr.push(el)))
  console.log(`inner${number}`, arr)
  return result;
}

request(arr1, 1);

console.log("outer1", arr1)

await request(arr2, 2);

console.log("outer2", arr2)

request(arr3, 3).then(()=>{
  console.log("then3",arr3)
})
console.log("outer3", arr3)
}

main();

【讨论】:

    【解决方案3】:

    我认为问题在于 console.log() 在填充数组之前被触发,并且因为 console.log 使用引用它打印数组的两个状态(当它为空时,以及在填充它之后用 .map )

    你可以测试这段代码吗? 控制台直接在循环之后

    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
           console.log(images);
        }
    
        request();
    
    }
    

    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
               console.log(images);
            }
    
            request();
    
        }
        
        loadInitialImages();

    【讨论】:

      猜你喜欢
      • 2012-09-29
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 2020-05-14
      相关资源
      最近更新 更多