【问题标题】:JS logical issues in condition条件中的 JS 逻辑问题
【发布时间】:2016-08-20 12:59:18
【问题描述】:

我正在构建一个使用 Kinvey mbaas 作为数据库的聊天应用程序。我有一个存储聊天的集合,其中包含以下数据列:_id、firstUser、otherUsers、history。到目前为止的想法是:当发布消息时,请求 GET 以查找两个用户之间是否存在聊天。 GET 获取整个集合并遍历条目并检查 firstUser 和 otherUsers 是否匹配。这就是问题所在:它们永远不匹配。代码如下:

for (let entity = 0; entity < response.length; entity++) {
console.log('DEV_firstUser: ' 
                 + response[entity]['firstUser'] + '|' + firstUser);
    console.log('DEV_otherUsers: |' 
                 + response[entity]['otherUsers'] + '|' + otherUsers + "|");

    console.log(response[entity]['firstUser'] === firstUser);
    console.log(response[entity]['otherUsers'] === otherUsers);
    // The problematic condition - the logs above are demonstrations.
    if (response[entity]['firstUser'] === firstUser 
            && response[entity]['otherUsers'] === otherUsers) {
                id = response[entity]['_id'];
                console.log('DEV_id: ' + id);
                index = entity;
                console.log(response[index][id]);
            }
    }

'response' 是集合——我可以看到的对象数组。 “实体”很简单——集合中的每个实体。 'otherUsers' 是数组。

这是我在控制台上得到的:

DEV_firstUser: alex|alex
DEV_otherUsers:|Ganka|Ganka|
true
false

【问题讨论】:

  • 请把它归结为几十行代码。

标签: javascript logical-operators kinvey


【解决方案1】:

您的代码存在两个问题(免责声明:答案基于问题的原始版本)。

firstUser比较

console.log('DEV_firstUserComparison: ' 
    + response[entity]['firstUser'] == firstUser);

产生false,因为+ has a higher precedence than == or ===,所以您实际上是在将字符串与用户对象进行比较(请注意,您在输出中也看不到“DEV_firstUserComparison:”)。

相反,将比较放在括号中:

console.log('DEV_firstUserComparison: ' 
        + (response[entity]['firstUser'] == firstUser));

短sn-p来演示问题:

console.log('foo' === 'foo');      //true
console.log('f' + 'oo' === 'foo'); //true

其他用户比较

即使在解决了第一个问题之后

console.log('DEV_otherUsersComparison: ' 
    + (response[entity]['otherUsers'] == otherUsers));

仍然返回false。这是因为otherUsers 是一个数组,您不能简单地将它们与== 进行比较。

相反,您还有其他一些选择。有关详细信息,请参阅 Stack Overflow 上的以下问题:

基本上:要么编写自己的比较方法,要么在比较之前将两个数组都转换为字符串(当元素的顺序不同时,这将不起作用)。

您的用例最简单的方法可能是:

response[entity]['otherUsers'].length == otherUsers.length
  && response[entity]['otherUsers'].every(function(v, i) { return v == otherUsers[i]})

再次,一个简短的 sn-p 演示:

var array1 = ['foo', 'bar'];
var array2 = ['foo', 'bar'];

function eq(a1, a2) {
  return a1.length == a2.length && a1.every(function(v, i) {
    return v === a2[i]
  });
}

console.log(array1 == array2);   //false
console.log(eq(array1, array2)); //true

【讨论】:

  • 很高兴知道,但为什么我的情况不起作用?
  • 那么服务器上的数据是由先前执行完全相同的函数创建的,因此它应该是相等的。我知道它不起作用,因为我查看每次迭代的控制台打印。如果你想看看 GitHub:github.com/AwesomeChat-devs/Awesome-chat/tree/Alex
  • 同时我会尝试在帖子中添加更多信息以便于澄清。
  • 是的,它是一个数组,因为我想要在一个聊天中添加多个用户的功能。但是看不到问题,只要在BD中保存为数组即可。
  • 查看我的更新答案。您不能简单地将数组与== 进行比较。
猜你喜欢
  • 2021-12-18
  • 2021-02-20
  • 1970-01-01
  • 2013-11-01
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
相关资源
最近更新 更多