javascript - 有没有办法使用另一个数组的元素动态创建一个新数组?
问题描述
因此,我正在创建一个表格,用户将在该表格上使用他们的选项填写表格的标题。对于这个例子,假设我想创建 3 个标题作为选项:“fruits”、“desserts”和“others”。
“申请人”将为这些标题填写他们的答案。
我要解决的问题如下:我需要对这些答案进行排序,并且我想将标头用作数组的变量,然后用答案填充该数组,例如:
let fruits = [];
fruits.push(*applicant's answers*);
我可以在表格准备好填充后创建一个带有标题的数组,例如“标题 = [水果,甜点,其他]”,但我不知道如何创建“水果 = []”或“甜点 = [ ]”,因为在表格填满并准备好回答之前,我不知道标题。
有没有办法解决这个问题,或者我需要用另一种方式解决它?
解决方案
您可以在单击输入条目时使用事件侦听器来运行函数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>
推荐阅读
- python - `isinstance(x, y)` 和 `x.__class__ == y` 之间的区别
- javascript - 在asp.net core mvc中将数据从部分视图传递到其父视图
- javascript - Firestore 从动态键字段或变量中获取值
- java - 比较两个充满相似数据的 avro 文件时,如何跳过同步标记?
- c# - sqlite 是否在选择查询结果中添加任何元数据信息?
- spring-boot - 如何将 RequestHeader 与执行器端点一起使用?
- javascript - DevExtreme React - 防止使用 useState 进行渲染
- linux - x86 NASM | 循环输入仅在第一次和第三次工作
- javascript - Redux Saga - React Infinite Scroll - 加载时的两个 api 调用
- asp.net-mvc - 默认身份与 JWT 冲突