尝试在我的LobbyQueue类中访问和比较对象属性的值。我已经成功地将数据从server.js添加到阵列,并记录下来。但是当我尝试使用LobbyQueue类中的方法访问并比较数组中对象的属性值时,我得到了undefined
作为数组索引。
我尝试从Queue类内部遍历数组的内容。这是我得到未定义的
的地方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);
}
});
...
我希望hasUser()
可以防止创建重复的连接。但当用户名已存在于队列中时,它不返回true
。就像用户在数组上循环时不存在一样。但是由于队列已登录到控制台,并且用户名和连接ID在那里,所以我不确定发生了什么。
答案 0 :(得分:1)
您需要将条件更改为
typeof this.players[i]['username'] === "undefined"
因为您需要访问属性名称“用户名”
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...");
}
}
}
答案 1 :(得分:0)
def verify(number):
return str(number).startswith("4")