簡體   English   中英

循環填充Javascript-Object鍵/值嗎?

[英]Populating Javascript-Object keys/values in loop?

我想做這樣的事情:

let obj = [];

for(let i=0;i<4;i++) {

// doing some stuff here ...
// and then, finally:

obj[i].words = wordsOfSentence;
}

但是,這給了我一個錯誤。

無法設置未定義的屬性“單詞”

現在,我像這樣解決它:

let obj = [{}, {}, {}, {}];

for(let i=0;i<4;i++) {

// doing some stuff here ...
// and then, finally:

obj[i].words = wordsOfSentence;
}

...但這意味着我必須總是總是事先將一個空對象推入數組? 什么是標准/優雅的解決方案?

在存儲任何鍵值對之前,必須必須創建一個空白的JSON對象,然后才能將JSON對象壓入數組。

let objects = [];
for (let i = 0; i < 4; i++) {
    objects[i] = {};
    objects[i].words = 'wordsOfSentence';  
    objects.push(objects[i]);  

}

console.log(objects);

創建對象,然后將其添加到數組中:

let obj = [];

for(let i=0;i<4;i++) {

// doing some stuff here ...
// and then, finally:
const newObj = { words: wordsOfSentence }
obj[i] = newObj;
}

您可以使用if語句

if( obj[i] ){
  obj[i].words = wordsOfSentence;
}

或者,您可以在訪問之前指定默認值

obj[i] = obj[i] || {}

您可以在每次迭代中簡單地推送一個新對象。

let objects = [];

for (let i = 0; i < 4; i++) {
    objects.push({words: wordsOfSentence});
}
let _obj = {};
_obj.words = [];
for (let i = 0; i < 4; i++) {    
    _obj.words.push('WordsOfSentense');
}
console.log(_obj);

這應該有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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