我是 JavaScript 的新手。我在谷歌和 stackoverflow 中搜索,但找不到解释。 我有一个必须保存在 json 中的输入,我不想在控制台中显示它。 我已将输入中的元素添加到数组中,但它仍在添加一个数组。 我想要这样的东西:
[
{"id":"1","name":"Anna"},
{"id":"2","name":"Mark"}
]
当我在现场检查它并单击“删除”按钮时,我想从数组中删除一个对象。
var arr = [];
function addTo() {
arr.push(document.getElementById("index").value);
arr.push(document.getElementById("name").value);
arr.push(document.getElementById("surname").value);
console.log(arr);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<select id="index" name="index">
<option hidden="" >Index</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<input placeholder="Name" type="text" id="name"/>
<input placeholder="Surname" type="text" id="surname"/>
<input type="button" onclick="remove()" value="Delete"/>
<input type="button" onclick="addTo()" value="Add"/>
</body>
</html>
最佳答案
此代码具有删除功能并检查现有项目:
function remove() {
var obj={
'index': document.getElementById("index").value
};
for(var i = arr.length - 1; i >= 0; i--) {
if(arr[i]['index']===obj['index']) {
arr.splice(i, 1);
}
}
console.log(arr);
}
function addTo() {
var obj={
'index': document.getElementById("index").value,
'name': document.getElementById("name").value,
'surname': document.getElementById("surname").value
};
if (!arr.some(e=>e['index']==obj['index']))
// add new
arr.push(obj);
else
// replace existing
arr[arr.map((e, i) => [i, e]).filter(e => e[1]['index']==obj['index'])[0][0]] = obj
console.log(arr);
}
var arr = [];
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label for="index">Index:</label>
<select id="index" name="index">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<input placeholder="Name" type="text" id="name"/>
<input placeholder="Surname" type="text" id="surname"/>
<input type="button" onclick="remove()" value="Delete"/>
<input type="button" onclick="addTo()" value="Add"/>
</body>
</html>
关于javascript - 在javascript中将对象推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54327676/