D.C*_*sta -1 javascript if-statement
我有这个简单的if语句比较两个对象属性(字符串):
if(client.room == sender.room){ /*Doesn't work*/ }
Run Code Online (Sandbox Code Playgroud)
我很惊讶它们没有通过所以我调试:
console.log(client.room + " == " + sender.room);
Run Code Online (Sandbox Code Playgroud)
输出是正确的:
#General == #General
Run Code Online (Sandbox Code Playgroud)
所以我尝试了很多东西,但仍然无效......
然后我尝试了这个:
var clientRoom = client.room;
if(clientRoom == '#General'){ /*Work!*/ }
if(client.room == '#General'){ /*Work!*/ }
Run Code Online (Sandbox Code Playgroud)
但我仍然被卡住......我如何比较这两个对象属性,看看它们是否相等?
这听起来像client.room和sender.room是对象与toString方法.两个不同的对象彼此不==相同,即使它们具有相同的内容和toString匹配.
你的client.room == "#General"作品因为==强迫它的操作数试图使它们成为同一类型.在这种情况下,它强制client.room转换为字符串(via client.room's toString).
您需要确定要用于确定对象是否等效的标准,并在比较它们时使用这些标准.您可以将其封装在equals方法或类似方法中.
问题的插图:
class Room {
constructor(name) {
this.name = name;
}
toString() {
return "#" + this.name;
}
}
const room1 = new Room("General");
const room2 = new Room("General");
console.log(room1 == room2); // false
console.log(room1 + " - " + room2); // #General - #General
console.log(room1 == "#General") // trueRun Code Online (Sandbox Code Playgroud)
或者在ES5语法中:
function Room(name) {
this.name = name;
}
Room.prototype.toString = function() {
return "#" + this.name;
};
var room1 = new Room("General");
var room2 = new Room("General");
console.log(room1 == room2); // false
console.log(room1 + " - " + room2); // #General - #General
console.log(room1 == "#General") // trueRun Code Online (Sandbox Code Playgroud)
添加equals和使用它的插图:
class Room {
constructor(name) {
this.name = name;
}
toString() {
return "#" + this.name;
}
equals(other) {
return other && other.name === this.name;
}
}
const room1 = new Room("General");
const room2 = new Room("General");
const room3 = new Room("SomethingElse");
console.log(room1 == room2); // false
console.log(room1.equals(room2)); // true
console.log(room1.equals(room3)); // falseRun Code Online (Sandbox Code Playgroud)
或者在ES5语法中:
function Room(name) {
this.name = name;
}
Room.prototype.toString = function() {
return "#" + this.name;
};
Room.prototype.equals = function(other) {
return other && other.name === this.name;
};
var room1 = new Room("General");
var room2 = new Room("General");
var room3 = new Room("SomethingElse");
console.log(room1 == room2); // false
console.log(room1.equals(room2)); // true
console.log(room1.equals(room3)); // falseRun Code Online (Sandbox Code Playgroud)