[英]How can i change object's item value in a loop in javascript?
我有類別列表。 每個類別是這樣的:
{
id,
name,
info
}
我想在 http 獲取請求后遍歷列表並更改飲食類別的信息。 我已經搜索並閱讀了類似的問題,但沒有任何效果。 信息總是有它的初始值
在下面的片段中:
categories
數組,並在獲取數據后更新info
屬性。筆記:
這里的一個常見錯誤可能是您在async
任務完成之前記錄了categories
數組。
因此,在下面的代碼中,如果我替換getData().then(() => console.log(categories));
通過getData(); console.log(categories);
getData(); console.log(categories);
那么我不會看到info
的更新值。
const categories = [ { id: 1, name: "delectus aut autem", info: "not fetched", url: "https://jsonplaceholder.typicode.com/todos/1", }, { id: 2, name: "quis ut nam facilis", info: "not fetched", url: "https://jsonplaceholder.typicode.com/todos/2", }, ]; const getData = async () => { for (let cat of categories) { const res = await fetch(cat.url); const json = await res.json(); cat.info = "fetched"; } }; getData().then(() => console.log(categories));
您可以使用forEach
,如下所示:
arr.forEach(function(part, index) {
this[index] = "hello world";
}, arr); // use arr as this
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.