繁体   English   中英

将new作为对象推入数组

[英]pushing new to a array as a object

我需要了解如何将几个键值对推入对象中的数组。

该对象如下:

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中将其显示为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);

您必须定位输入元素以获取值。 然后使用该值形成对象,并使用Array.prototype.push()将对象压入数组:

document.querySelector('[name="inputTodo"]').value

 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 }] let newTodo = '' let status = false //Insert new todo document.querySelector('#addTodo').addEventListener('submit', function (e) { e.preventDefault() newTodo = document.querySelector('[name="inputTodo"]').value; todos.push({text: newTodo, completed: false}); console.log(todos) }) 
 <form action="" id="addTodo"> <input type="text" name="inputTodo" placeholder="Insert new todo"> <button>Add Todo</button> </form> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM