基本上,我最近开始使用WebSockets,每当我从客户端->服务器发送创建新消息所需的JSON数据时,我都会首先使用提供的ID检查用户是否在聊天中从客户端返回的结果为false,即使此时正在检查的ID都相同
例如'abc'=='abc'将返回false
Checking: 5c2e13ee193dac483851677b === 5c2e13ee193dac483851677b -> false.
我尝试过控制台记录城市和city_id(由客户端提供)的类型,它们都是对象。我进行了.toString()转换,以获取字符串,然后进行了.trim()转换,即使不需要.toString(),因为它们已经是字符串了
public isInCity(city_id: string) {
for(const planet of this.user.planets) {
console.log(`Checking ${(planet as IPlanet)._id}`)
for(const city of (planet as IPlanet).cities) {
if(typeof city === 'string') {
console.log(`\tChecking - s: ${city} === ${city_id} -> ${city === city_id}`)
if(city == city_id) return true;
} else {
console.log(`\tChecking: ${city._id} === ${city_id} -> ${city._id === city_id}.`)
if(city._id === city_id) return true;
}
}
}
}
预期结果应该是:
Checking: 5c2e13ee193dac483851677b === 5c2e13ee193dac483851677b -> false.
应返回true
Checking 5c2df2a01260fa4aacb185f1
Checking 5c2df2a01260fa4aacb185f2
Checking 5c2df2a11260fa4aacb185f3
Checking: 5c2df7b05eed7a168c402bbb === 5c2e13ee193dac483851677b ->
false.
Checking: 5c2df7d2d97d783da00dddd1 === 5c2e13ee193dac483851677b ->
false.
Checking: 5c2df7dee32f114614342f9f === 5c2e13ee193dac483851677b ->
false.
Checking: 5c2df7ef08e3185224ac53db === 5c2e13ee193dac483851677b ->
false.
Checking: 5c2df8986a91193170411e1d === 5c2e13ee193dac483851677b ->
false.
Checking: 5c2e13ee193dac483851677b === 5c2e13ee193dac483851677b ->
false.
不太确定是什么原因引起的,我花了很长时间试图弄清楚是什么,但我只是无法弄清楚
答案 0 :(得分:-3)
如果您知道两者的类型可能不同,但值可以相同也可以不相同,那么
use == instead of ===
因为 ==
不会检查类型