JavaScript if语句不起作用

时间:2017-04-05 09:37:12

标签: javascript if-statement

我有这个简单的if语句来比较两个对象属性(字符串):

if(client.room == sender.room){ /*Doesn't work*/ }

我很惊讶他们没有通过所以我调试:

console.log(client.room + " == " + sender.room);

输出正确:

#General == #General

所以我尝试了很多东西,但仍然不起作用......

然后我尝试了这个:

var clientRoom = client.room;
if(clientRoom == '#General'){ /*Work!*/ }

if(client.room == '#General'){ /*Work!*/ }

但是我仍然被卡住......如何比较这两个对象属性以确定它们是否相等?

1 个答案:

答案 0 :(得分:5)

听起来client.roomsender.room是具有toString方法的对象。两个不同的对象彼此不==,即使它们具有相同的内容且toString匹配。

您的client.room == "#General"有效,因为==会强制其操作数尝试使它们成为相同的类型。在这种情况下,它会将client.room强制转换为字符串(通过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")    // true




或者在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")    // true




添加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));   // false




或者在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));   // false