javascript - 在数组中添加新对象
问题描述
这似乎很容易,但对我不起作用。我想在填充输入后在对象中添加新数组和名称。单击 OK 按钮时应添加新对象。例如:
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
);
推荐阅读
- php - 为什么 WooCommerce 中的dashboard.php 不能显示图像
- dart - Dart 中 Future 对象的机制
- javascript - React Contextprovider 强制更新 Video Element 来播放 Video
- git - 当具有更改文件的分支合并到主分支时,Git 不会引发合并冲突
- python - 带有日期选择器的 Python selenium
- javascript - 在 Promise.race() 中,失去承诺会发生什么?
- javascript - 意外的模板字符串表达式
- python - 如何以有效的方式将n维列表排序为一个列表
- r - 我有一个可以工作的函数,想在一个循环中为列表中的多个数据帧运行它,但不知道如何更新数据帧?
- regex - PowerShell 脚本检查所有目录的名称并在每个目录中创建子文件夹