首页 > 解决方案 > chrome控制台中数组的不同表示

问题描述

这是我的代码

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]

标签: javascriptarraysgoogle-chromeasync-awaitconsole.log

解决方案


由于您的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,您应该利用它的工作原理。您可以使用它来生成整个数组,而无需使用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));
}

推荐阅读