首页 > 解决方案 > 在数组中添加新对象

问题描述

这似乎很容易,但对我不起作用。我想在填充输入后在对象中添加新数组和名称。单击 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);
}

标签: javascriptarrays

解决方案


您需要创建一个新对象,并调用push数组,而不是其中的对象:

    arr.push(
// −^^^^^^^^
        {                         // This part is an "object
            name: input.value,    // literal" that creates
            point: ''             // a new object with these
        }                         // properties in it
    );

推荐阅读