简体   繁体   English

如何仅推送一个 object 并使用 JavaScript 将其更新为数组?

[英]How to Push only one object and update it into Array using JavaScript?

I am creating simple App using Vanilla JavaScript, I have some issue, Let's explain my problem,In the beginning i have empty array, I want to push some values from Input field, and it's works fine, but i want to push only one object into arrOfObj:[] , that means i want replace old value by new value, without changing the length.我正在使用 Vanilla JavaScript 创建简单的应用程序,我有一些问题,让我们解释一下我的问题,一开始我有空数组,我想从输入字段中推送一些值,它工作正常,但我只想推送一个 object进入arrOfObj:[] ,这意味着我想用新值替换旧值,而不改变长度。

 var arrOfObj = []; function pushObject() { var inputVal = document.getElementById('mainInput').value; arrOfObj.push({ id: 1, value: inputVal }); console.log(arrOfObj); }
 <button onclick="pushObject()">click</button> <input type="text" id="mainInput">

I think instead of using push , you can directly replace the first index with your new object我想不用push ,你可以直接用你的新 object 替换第一个索引

    var arrOfObj = [];
    function pushObject(){
     var inputVal = document.getElementById('mainInput').value
     //replace the first value of array
     arrOfObj[0] = {'id':1, 'value':inputVal};
      console.log(arrOfObj)
    }

    
    <button onclick="pushObject()">click</button>
    <input type="text" id="mainInput">

You can achieve this by simply updating the 0th element of your array if there is one.您可以通过简单地更新数组的第 0 个元素(如果有的话)来实现这一点。

 var arrOfObj = []; function pushObject(){ var inputVal = document.getElementById('mainInput').value if (arrOfObj[0]) { arrOfObj[0].value = inputVal } else { arrOfObj.push({'id':1, 'value':inputVal}) } console.log(arrOfObj) }
 <button onclick="pushObject()">click</button> <input type="text" id="mainInput">

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

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