首页 > 解决方案 > 有没有办法使用另一个数组的元素动态创建一个新数组?

问题描述

因此,我正在创建一个表格,用户将在该表格上使用他们的选项填写表格的标题。对于这个例子,假设我想创建 3 个标题作为选项:“fruits”、“desserts”和“others”。

“申请人”将为这些标题填写他们的答案。

我要解决的问题如下:我需要对这些答案进行排序,并且我想将标头用作数组的变量,然后用答案填充该数组,例如:

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

我可以在表格准备好填充后创建一个带有标题的数组,例如“标题 = [水果,甜点,其他]”,但我不知道如何创建“水果 = []”或“甜点 = [ ]”,因为在表格填满并准备好回答之前,我不知道标题。

有没有办法解决这个问题,或者我需要用另一种方式解决它?

标签: javascriptjquery

解决方案


您可以在单击输入条目时使用事件侦听器来运行函数arr.reduce()以迭代标题数组,传入将两个数组组合为对象的输入值,然后将对象推入另一个数组,每个新条目你的投入。

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>


推荐阅读