向对象添加新值

时间:2016-06-20 04:48:05

标签: javascript html object add

我有一个数组对象并希望它可以添加不同用户的其他用户名和密码。如果用户名或密码不存在,它将自动创建。我以为我的数组对象会像这样工作: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!");
            }
        }
    });
});

1 个答案:

答案 0 :(得分:1)

在向其添加新对象时,我不确定您是否正确访问了数组。它应该是:

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

因为length总是比最后一个索引多一个,并且是你想用新对象填充的索引。如果您改为使用:

userInfo [userInfo.length + 1] [&#34;用户名&#34;] =用户名;

然后你正在跳过一个索引。 此外,最好先在该索引处创建一个对象:

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

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