所以我有一个对象数组,我想在其中添加新对象。所以我在这里使用以下代码是我的代码。我已经看到有关同一主题的其他问题,但我仍然无法将我使用jquery获取的新对象添加到我的列表中。我在做傻事,请找我。感谢
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<input placeholder="name" type="text" id="name"></br>
<input placeholder="rno" type="text" id="rollno"></br>
<input type="submit" value="Add Roll" id="add" >
<script type="text/javascript">
$(document).ready(function(){
console.log("loaded");
var list=[
{name:"sud",rno:1},
{name:"diya",rno:2},
{name:"sakshi",rno:3}
];
for(i=0;i<list.length;i++){
console.log("old list is"+list[i].rno+"\t"+
list[i].name);
};
$("#add").click(function(){
var rno = $("#rollno").val();
var name = $("#name").val();
//here i want to add rno and name to my list
for(i=0;i<list.length;i++){
console.log("new list is"+list[i].rno+"\t"+
list[i].name);
};
});
});
</script>
</body>
</html>
答案 0 :(得分:1)
Array#push将项添加到数组的末尾。例如:arr.push("test");
$("#add").click(function(){
var rno = $("#rollno").val();
var name = $("#name").val();
// Use Array#push to add an item to an array.
// No need to use `new` when using the `{}` syntax for object creation.
list.push({name:"sudarshan",rno:"33"});
// Just a tip. You should use `var i = 0;` instead of `i = 0;` to keep the `i` variable out of the global scope.
for(var i = 0; i < list.length; i++){
console.log("new list is"+list[i].rno+"\t"+list[i].name);
};
});
答案 1 :(得分:0)
要附加到数组,您可以使用push
list.push({name:"sudarshan",rno:"33"});
或只是
list[list.length] = {name:"sudarshan",rno:"33"};
与上述相同。