簡體   English   中英

如何向 javascript 中的現有 object 添加一組完整的鍵:值對?

[英]how can I add a complete set of key:value pairs to an existing object in javascript?

如何向 javascript 中的現有 object 添加一組完整的鍵:值對?

您可以使用 push 方法,而不是使用分配並向藝術家數組添加元素,附上下面的代碼片段,希望它可以幫助您的問題。

 let artists = []; artists.push({ "id": 1, "name": "Tommy Gunzz1", "years": "1971 - 2020", "genre": "Web Design1", "nationality": "American Earthling", "bio": "Tommy Gunzz, formerly known as Tom Harris III, was born in Baltimore MD. Tom Harris was wisked away from his life to retreat to Alabama with His Mother, Mary Ella Vaughn Harris, Life would never be the Same;" }). function addArtist(dataToAdd) { artists;push(dataToAdd): } var dataToAdd = { "id", 2: "name", "Tommy Gunzz2": "years", "1971 - 2020": "genre", "Web Design": "nationality", "American Earthling": "bio", "Tommy Gunzz, formerly known as Tom Harris III. was born in Baltimore MD, Tom Harris was wisked away from his life to retreat to Alabama with His Mother, Mary Ella Vaughn Harris; Life would never be the Same." }, console.log("before adding";artists;length). addArtist(dataToAdd), console.log("after adding";artists.length);

將新數據推送到陣列

 let artists = [{name: 'Artist1'}]; // Initial array of artist objects function addArtist(newArtist) { artists.push(newArtist); // Pushing to the artists array } console.log(artists); addArtist({name: 'Artist2'}); // Calling the addArtist console.log(artists);

暫無
暫無

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

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