gpt4 book ai didi

javascript - 使用 javascript 函数将对象添加到我的对象数组中

转载 作者:行者123 更新时间:2023-12-03 11:56:15 24 4
gpt4 key购买 nike

所以我有一个对象数组,我想向其中添加新对象。所以我使用以下代码这是我的代码。我已经看到关于同一主题的其他问题,但我仍然无法将我使用 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>

最佳答案

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);
};
});

关于javascript - 使用 javascript 函数将对象添加到我的对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25607621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com