javascript - 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]
解决方案
由于您的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));
}
推荐阅读
- html - 仅在被点击的元素上添加 [ngClass]
- python - 在不刷新网页的情况下刷新源代码
- python - 使用带有 'mean()' 和 'median()' 的 eval 函数
- flutter - 我的 Flutter Web 应用程序中的 CORS 策略阻止了对 XMLHttpRequest 的访问
- ios - react-native 无法构建 ios: (error xcode Flipper) Typedef 重新定义不同类型 ('uint8_t' (aka 'unsigned char') vs 'enum clockid_t')
- or-tools - 护士调度:N 天内最大的无轮班序列必须 > X
- javascript - 根据他们的 id 调用对象并将结果附加到一个大的最终对象
- c - Microsoft Compiler C Program - 请帮助在编译期间使用 _Pragma 消息将宏参数(它是一个字符串)打印到构建日志
- sql - 如何使用 REGEXP_SUBSTR() 从 oracle 中的表中提取字符串的某些部分(条件不包括第一个空格的前面部分)
- python - while循环中的pop变量在完成后不会打印