【发布时间】:2022-01-20 13:05:15
【问题描述】:
以下程序会将输入中输入的文本添加到数组中,并在p 标记中显示该数组。当用户按下提交时,文本将被添加到数组中。我需要将其添加为包含索引和文本的对象。
目前,该数组将如下所示:['a', 'b', 'c']
我需要数组看起来像:[{"index": 0, "text": "a"}, {"index": 1, "text": "b"}]
let arr = [];
function addText() {
let text = document.getElementById('text').value;
arr.push(text);
res = document.getElementById('result-text').innerText = arr;
}
<input type="text" id="text" placeholder="Enter a text" />
<input type="submit" onclick="addText()" />
<p id="result-text"></p>
【问题讨论】:
标签: javascript html arrays json