gpt4 book ai didi

javascript - 向对象添加新值

转载 作者:行者123 更新时间:2023-12-03 06:41:57 25 4
gpt4 key购买 nike

我有一个数组对象,并且想要它,这样我就可以添加不同用户的其他用户名和密码。如果用户名或密码不存在,它将自动创建。我认为我的数组对象会像这样工作: userInfo[0]["username"] 是 user1,userInfo[1]["username"] 是 user2,等等。这是jsfiddle: https://jsfiddle.net/xkxn54bx/

HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="test.js"></script>
<title>Generation X</title>
</head>
<body>
<form method="post">
<label for="username">Username:</label><input type="text" name="user_name" id="username"><br />
<label for="password">Password:</label><input type="password" name="pass-word" id="password">
<input type="submit" id="submitbutton" value="Access">
</form>
</body>
</html>

JS:

var userInfo = [
{ username: "admin", password: "test" }
];

function addUser(username, password) {
userInfo[userInfo.length + 1]["username"] = username;
userInfo[userInfo.length + 1]["password"] = password;
}

$(document).ready(function() {
$('#submitbutton').click(function() {
var username = $('#username').val();
var password = $('#password').val();
for (i = 0; i < userInfo.length; i++) {
if (username == '' || password == '') {
alert("All fields are required!");
}
else if (username == userInfo[i]["username"]) {
if (password == userInfo[i]["password"]) {
alert("Welcome");
}
else {
alert("You have entered an invalid password!");
}
}
else {
addUser(username, password);
alert("Account created!");
}
}
});
});

最佳答案

我不确定在向数组添加新对象时是否正确访问数组。应该是这样的:

function addUser(username, password) {
userInfo[userInfo.length - 1]["username"] = username;
userInfo[userInfo.length - 1]["password"] = password;
}

因为长度始终比最后一个索引大一,并且这就是您想要用新对象填充的索引。如果您改为使用:

userInfo[userInfo.length + 1]["用户名"] = 用户名;

那么您将跳过一个索引。另外,最好先在该索引处创建一个对象:

function addUser(username, password) {
userInfo[userInfo.length]={};

userInfo[userInfo.length - 1]["username"] = username;
userInfo[userInfo.length - 1]["password"] = password;
}

关于javascript - 向对象添加新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37914780/

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