gpt4 book ai didi

javascript - 为什么不是一个包含所有项目的数组,而是每个项目的数组?

转载 作者:行者123 更新时间:2023-12-04 01:20:29 25 4
gpt4 key购买 nike

我想将所有项目数据放入一个数组中。但是,当我尝试时,它只是为每个项目创建一个数组。

async function final() {
const response = await fetch('/api');
const data = await response.json();
console.log(data)

for (item of data) {
const num = item.atomicNumber;
const arr = []
arr.push(num)

console.log(arr)
}

}

最佳答案

因为您正在循环内创建一个新数组。逐步分析您自己的代码并了解每一行的作用是成为一名优秀开发人员所必需的:-)。让我们来分析一下:

async function final() {
const response = await fetch('/api');
const data = await response.json();
console.log(data)

// Until here everything is fine

// You define a loop which will run from this point each time
for (item of data) {
const num = item.atomicNumber;

// You are creating a new array inside the loop. The loop, as its name says, will run one time per item.
const arr = []
arr.push(num)

console.log(arr)
}
}

要解决这个问题,只需将数组移到循环之外,这样它就只运行一次:

async function final() {
const response = await fetch('/api');
const data = await response.json();
console.log(data)

// We create the array outside the loop
const arr = []

// Then define a loop which will run from this point each time
for (let item of data) { // Don't forget to define variables with the proper keyword (in this case, "let" is enough).
const num = item.atomicNumber;
arr.push(num)
}

// We log the array when the loop has ended, so it logs only one time
console.log(arr)
}

关于javascript - 为什么不是一个包含所有项目的数组,而是每个项目的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59594681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com