我认为标题已经说明了一切。我需要将输入值保存在一个对象中,然后将该对象保存在一个数组中。
<html>
<head>
<title>Teste</title>
</head>
<script>
function vai(){
var pessoa = {
nome = document.getElementById('nome').value,
idade = document.getElementById('idade').value
};
var i = 0;
var pessoas = [];
pessoas[i] = pessoa{};
i++;
}
</script>
<body>
<label>Digite seu nome aqui</label>
<input type='text' id='nome' placeholder='aquii'>
<label>Digite sua idade aqui</label>
<input type='text' id='idade' placeholder='aquii'>
<button onclick='vai()'>
Teste aqui
</button>
</body>
</html>
最佳答案
您应该在全局环境中(函数外)声明数组。您在对象内部也有一些语法问题(应该是 :
而不是 =
)。然后你可以简单地 push()
每次单击按钮时将对象放入数组中。
试试下面的方法:
var pessoas = [];
function vai(){
var pessoa = {
nome: document.getElementById('nome').value,
idade: document.getElementById('idade').value
};
pessoas.push(pessoa);
console.log(pessoas);
}
<label>Digite seu nome aqui</label>
<input type='text' id='nome' placeholder='aquii'>
<label>Digite sua idade aqui</label>
<input type='text' id='idade' placeholder='aquii'>
<button onclick='vai()'>
Teste aqui
</button>
您通过维护变量而不使用 push()
的方法几乎是正确的,除了变量声明范围之外。您必须将其声明为全局变量。您可以将对象分配到当前位置并在每个函数调用中递增:
var pessoas = [];
var i = 0;
function vai(){
var pessoa = {
nome: document.getElementById('nome').value,
idade: document.getElementById('idade').value
};
pessoas[i] = pessoa;
i++;
console.log(pessoas);
}
<label>Digite seu nome aqui</label>
<input type='text' id='nome' placeholder='aquii'>
<label>Digite sua idade aqui</label>
<input type='text' id='idade' placeholder='aquii'>
<button onclick='vai()'>
Teste aqui
</button>
请注意:您也可以简单地使用 length
数组的属性作为当前索引,在这种情况下您确实需要维护变量:
var pessoas = [];
function vai(){
var pessoa = {
nome: document.getElementById('nome').value,
idade: document.getElementById('idade').value
};
pessoas[pessoas.length] = pessoa;
console.log(pessoas);
}
<label>Digite seu nome aqui</label>
<input type='text' id='nome' placeholder='aquii'>
<label>Digite sua idade aqui</label>
<input type='text' id='idade' placeholder='aquii'>
<button onclick='vai()'>
Teste aqui
</button>
关于javascript - 如何使用纯 javascript 将输入值保存在 JSON 对象中,然后将其保存在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56301562/