在数组中添加新对象

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

}


RISEBY
浏览 690回答 1
1回答

汪汪一只猫

您需要创建一个新对象,并调用push数组,而不是其中的对象:&nbsp; &nbsp; arr.push(// −^^^^^^^^&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// This part is an "object&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: input.value,&nbsp; &nbsp; // literal" that creates&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; point: ''&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// a new object with these&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// properties in it&nbsp; &nbsp; );
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript