I have this code:
var users = [];
users.push({
username: "admin",
password: "admin"
});
this.showAllUsers = function() {
console.log(users);
};
this.addUser = function(user) {
if('username' in user && 'password' in user) {
users.push({
username: user.username,
password: user.password
})
}
else {
throw "Invalid object";
}
};
this.isExist = function(user) {
console.log(users.indexOf({
username: "admin",
password: "admin"
}));
};
Why console log prints all the time -1 ? Users array contains array with object with property username: "admin: and password: "admin".
-
6Just a note - if you're intending to put passwords in some client side code, you may want to rethink what you're doing.James Thorpe– James Thorpe2015年09月08日 16:23:12 +00:00Commented Sep 8, 2015 at 16:23
-
You need to loop and check each property.epascarello– epascarello2015年09月08日 16:24:27 +00:00Commented Sep 8, 2015 at 16:24
-
you can't simply check object equality in javascript. stackoverflow.com/questions/201183/…Lee– Lee2015年09月08日 16:25:51 +00:00Commented Sep 8, 2015 at 16:25
3 Answers 3
The indexOf
method uses strict equals (===
). When you use {foo: bar}
, you create a new (unique) object that will not evaluate strictly equal to anything already in the array.
What you should do is iterate through the array and use a function to compare each object using deep equality. Simply, you could use something like:
function match(arr, ref) { // Take an array and a reference object
return arr.filter(function (cur) { // Select any items in the array...
return Object.keys(ref).every(function (key) { // Where all keys...
return ref[key] === cur[key]; // Have the same value in the item and reference
});
});
}
Comments
Take a look here indexOf.
And remember that managing passwords on the client side is security flaw.
Comments
this.isExist = function(user) {
console.log(users.indexOf({
username: "admin",
password: "admin"
}));
};
The problem here is that you're checking if the users array contains this new object you're creating. Since it's a new object, it's obviously not going to contain it. You need to check to see if the users object contains any object that has a username or password equal to "admin". Maybe something like
this.isExist = function(user) {
for(var x = 0; x < users.length; x++) {
var current = users[x];
if(current.username === user.username && current.password === user.password) {
return true;
}
}
return false;
};
Or, alternatively, you can simply use Linq.js, which helps a lot with these kind of queries. It's one of my favorite libraries.