我在搜索对象数组时遇到问题。基本上我的页面需要做的是使用我输入的信息创建一个新的“客户端”,例如全名、用户名、电子邮件和密码。这些客户端中的每一个都是数组中的对象,如下所示。
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe@hotmail.com","type":"client","password":"jdoe2"},
该客户端已在我的 js 文件中创建,我需要做的是创建一个新对象以添加到具有相同结构的数组中。例如,
var clientlist = [{"username":"Peter","fullname":"Peter Jones",
"email":"peter.jones@hotmail.com","type":"client","password":"pjones1"},
我已经编写了代码,但它无法正常工作,当我运行 Firebug 时,我可以看到除了值为“”的用户名之外,所有元素都已正确添加。我似乎无法搜索用户名来查看我添加的用户名是否已经存在,这可能是语法错误。我将在下面留下完整的代码,并提前感谢您的帮助!
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe@hotmail.com","type":"client","password":"jdoe2"},
var Client = {};
function NewClient(){
var found;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
}else{
found = false;
}
}
if (found == true){
$("#msj").html("User already exists!");
}
else if(found == false){
Client["fullname"] = $("#fullname").val();
Client["username"] = user;
Client["email"] = $("#email").val();
Client["type"] = "client";
Client["password"] = $("#password").val();
clientlist[clientlist.length] = Client;
$("#msj").html("New client has been created");
}
}
最佳答案
你犯的一些错误:
- 忘记关闭
clientlist
数组 - 忘记实际推送新添加的客户端
下面的代码应该可以纠正您在此过程中犯的一些错误。
var clientlist = [{
"username": "John",
"fullname": "John Doe",
"email": "john.doe@hotmail.com",
"type": "client",
"password": "jdoe2"
}];
function NewClient() {
var found = false;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
} else {
found = false;
}
}
if (found) {
$("#msj").html("User already exists!");
} else {
var newUser = {
fullname: $("#fullname").val(),
username: user,
email: $("#email").val(),
type: "client",
password: $("#password").val()
}
clientlist.push(newUser);
$("#msj").html("New client has been created");
}
}
为你做了一个 fiddle : http://codepen.io/gabrielgodoy/pen/xOxoWw?editors=1011
关于javascript - Javascript 数组中对象的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37535622/