以下程序会将输入中输入的文本添加到数组中,并在p标签中显示该数组。当用户按下提交时,文本将被添加到数组中。我需要将它添加为包含索引和文本的对象。
目前,该数组将如下所示: ['a', 'b', 'c']
我需要数组看起来像: [{"index": 0, "text": "a"}, {"index": 1, "text": "b"}]
```javascript
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>
```
将文本作为对象添加到数组
let arr = [];
function addText() {
let text = document.getElementById('text').value;
arr.push({ index: arr.length, text });
res = document.getElementById('result-text').innerText = JSON.stringify(arr);
}