[英]Add new object in array
这似乎很容易,但对我不起作用。 我想在填充输入后在对象中添加新数组和名称。 单击“确定”按钮时应添加新对象。 例如:
let arr = [{
name: 'thomas',
point: ''
},
{
name: 'this should be value from input',
point: ''
}];
现在我有这个代码:
Name: <input type="text" id="input">
<button onclick="ok()">OK</button>
const input = document.querySelector('#input');
const arr = [{
name: 'Thomas',
point: ''
}];
function ok(){
arr['name'].push(input.value);
console.log(input.value);
console.log(arr);
}
您需要创建一个新对象,并在数组上调用push
,而不是其中的对象:
arr.push(
// −^^^^^^^^
{ // This part is an "object
name: input.value, // literal" that creates
point: '' // a new object with these
} // properties in it
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.