我需要了解如何将几个键值对推送到对象中的数组中。
对象如下:
const todos = [{
text: 'Order airline tickets',
completed: false
},{
text: 'Vaccine appointment',
completed: true
}, {
text: 'Order Visa',
completed: true
}, {
text: 'Book hotell',
completed: false
}, {
text: 'Book taxi to airport',
completed: true
}]
我创建了一个带有表单和文本输入的 html 页面来创建新项目数组:
<form action="" id="addTodo">
<input type="text" name="inputTodo" placeholder="Insert new todo">
<button>Add Todo</button>
</form>
js代码如下:
//Variable to store value from textbox for new todo
let newTodo = ''
let status = false
//Insert new todo
document.querySelector('#addTodo').addEventListener('submit', function (e) {
e.preventDefault()
newTodo = e.target.elements.inputTodo.value
//console.log(newTodo)
})
新待办事项的完成值始终为 false。 我有一个单独的函数,它循环遍历对象并将其显示在 div 中,其中 p 标签用于文本部分,单选按钮用于完成状态 false 或 true。
我需要学习的是如何插入表单的值并将其插入 todos.text 并获取 false 的硬编码值并将其插入 todos.completed。
谢谢
最佳答案
应该是这样的:
todos.push({
text: e.target.elements.inputTodo.value,
completed: false
});
或者,如果您想使用临时变量:
todos.push({
text: newTodo,
completed: status
});
您甚至可以定义一个新的临时对象并将其推送:
var newTodoObject = {
text: newTodo,
completed: status
}
todos.push(newTodoObject);
关于javascript - 将 new 作为对象推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54005863/