簡體   English   中英

如何在 javascript 的循環中更改對象的項目值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM