簡體   English   中英

有沒有辦法使用另一個數組的元素動態創建一個新數組?

[英]Is there a way to create a new array dynamically using elements of another array?

因此,我正在創建一個表,用戶將在該表上使用他們的選項填寫表的 header。 對於這個例子,假設我想創建 3 個標題作為選項:“fruits”、“desserts”和“others”。

“申請人”將為這些標題填寫他們的答案。

我要解決的問題如下:我需要對這些答案進行排序,並且我想使用 header 作為數組的變量,我會用答案填充該數組,例如:

let fruits = [];
fruits.push(*applicant's answers*);

我可以在表格准備好填充后創建一個帶有標題的數組,例如“headers = [fruits, desserts, others]”,但我不知道如何創建“fruits = []”或“desserts = [ ]”,因為在表格填滿並准備好回答之前,我不知道標題。

有沒有辦法解決這個問題,或者我需要用另一種方式解決它?

You can use an event listener on click of the input entries to run a function with arr.reduce() to iterate over an array of the titles, passing in the inputs values combining both arrays as an object, then push the object into another array隨着您輸入的每個新條目。

 const inputs = document.querySelectorAll('.inputs') const submit = document.getElementById('submit') const titles = ['fruits', 'deserts', 'others'] let entries = new Array() const combineArrays = (titles, input) => { return titles.reduce((acc, val, index) => { acc[val] = input[index].value return acc }, {}) } submit.addEventListener('click', () => { entries.push(combineArrays(titles, inputs)) if (entries.length > 0) { submit.value = 'Add more' } console.log(entries) })
 .titles { display: inline-block; width: 5rem; line-height: 2em; }
 <div><span class="titles">Fruits: </span><input class="fruits inputs" name="fruits" type="text"></div> <div><span class="titles">Deserts: </span><input class="deserts inputs" name="deserts" type="text"></div> <div><span class="titles">Others: </span><input class="others inputs" name="others" type="text"></div> <span class="titles"></span><input value="Add Entry" type="button" id="submit"></td>

暫無
暫無

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

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