Reputation: 2322
Trying to access and compare the value of an object's property inside my LobbyQueue class. I've successfully added data to the array from server.js, and logged it. but when I try to use a method from LobbyQueue class to access & compare an object's property value form the array, I get undefined
for the array index.
I've tried looping through the array's contents from inside the Queue class. this is where I'm getting undefined's
LobbyQueue.js:
class LobbyQueue {
constructor() {
this.players = [];
}
enqueue(player) {
this.players.push(player);
}
dequeue() {
if (this.isEmpty()) {
return "Wait List is Empty";
}
return this.players.shift();
}
hasUser(username) {
if (this.players.length == 0) {
return false;
} else {
for (var i = 0; i < this.players.length; ++i) {
if (typeof this.players[i][username] === "undefined") {
console.log("this.players[" + i + "][username] is undefined...");
if (this.players[i][username] === username) {
console.log("username comparison entered...");
}
}
}
}
}
}
module.exports = LobbyQueue;
server.js:
const queue = new LobbyQueue();
var gameRooms = [];
io.on("connection", socket => {
console.log("a user connected..." + "\n");
socket.on("addPlayer", username => {
if (queue.hasUser(username)) {
console.log("user already in queue...");
} else {
console.log("New user joined: " + username);
queue.enqueue({
username: username,
id: socket.id
});
socket.join("lobby");
const players = queue.getAll();
console.log("Players in queue: " + "\n" + JSON.stringify(players));
io.sockets.in("lobby").emit("players", players);
}
});
...
I expect hasUser()
to prevent a duplicate connection being created. but its not returning true
when the username already exists in the queue. it's as if the user doesn't exist when it loops over the array. but since the queue was logged to the console and the username and connection id are there, Im not sure whats going on.
Upvotes: 0
Views: 92
Reputation: 18975
You need change condition to
typeof this.players[i]['username'] === "undefined"
Because you need access property name 'username'
for (var i = 0; i < this.players.length; ++i) {
if (typeof this.players[i]['username'] === "undefined") {
console.log("this.players[" + i + "][username] is undefined...");
if (this.players[i]['username'] === username) {
console.log("username comparison entered...");
}
}
}
Upvotes: 1
Reputation: 984
hasPlayer(username) {
return this.players.find(player => player['username'] == username) != null;
}
Upvotes: 0