我使用以下方法将输入存储在对象(键和值)上:
const object1 = {
un: inp.value,
pw: inpw.value
};
var myJSON = JSON.stringify(object1);
var myObj = JSON.parse(myJSON);
现在我希望每个对象都存储在一个数组中,例如第一个输入是:
- {"un":"john","pw":"smith"}
它将被存储到 array[0]
例如,第二个输入将是:
- {"un":"beth","pw":"sebastian"}
等等..
所以当我调用 array[0] 时,它只会显示 {"un":"john","pw":"smith"}'
所以这是我的代码:
<form action="" autocomplete="on">
<div class="" style="width:300px;">
<input id="myInput" type="text" name="myInput" placeholder="Input" autocomplete="input">
<input id="myPW" type="password" name="myPassword" placeholder="Password" autocomplete="password">
</div>
<input id="button" type="submit">
</form>
<h2>Username</h2>
<p id="uname"></p>
<h2>Password</h2>
<p id="pass"></p>
<h2>Data</h2>
<ol id="val"></ol>
<h2>Array</h2>
<ol id="arr"></ol>
<script>
var myButton = document.getElementById('button');
var inp = document.getElementById('myInput');
var inpw = document.getElementById('myPW');
myButton.addEventListener('click', function(event) {
event.preventDefault();
const object1 = {
un: inp.value,
pw: inpw.value
};
var myJSON = JSON.stringify(object1);
var myObj = JSON.parse(myJSON);
val.innerHTML += '<li>' + myJSON + '</li>';
//it should be in this part where it document the myJSON
cookies = [];
cookies.push(myJSON);
for (var i = 0; i < cookies.length; i++) {
arr.innerHTML += '<li>' + cookies[i] + '</li>';
}
});
我怎样才能解决这个问题?
只需创建一个数组并将值推送给它:
var inputData = [];
var myJSON = JSON.stringify(object1);
var myObj = JSON.parse(myJSON);
inputData.push(myObj)
JSfiddle:https ://jsfiddle.net/Lya0nu1t/1/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句