【问题标题】:How would I change the logic of this if statement to work [duplicate]我将如何更改此 if 语句的逻辑以使其工作[重复]
【发布时间】:2013-12-03 16:36:00
【问题描述】:

我想检查一个数组元素是否包含在另一个数组中,到目前为止我已经尝试了这两种方法,即使 ignoreList 包含该元素,它们也都只是执行。

for (email in emailList) {

        if(!(emailList[email].to.toLowerCase() in ignoreList)){
        //if(ignoreList.indexOf(emailList[email].to.toLowerCase()) == -1){

我尝试了注释和未注释的方式。

从高层次的角度来看。我想检查 emailList 中的电子邮件是否包含在 ignoreList 中,如果它在 ignoreList 中,那么我不希望它执行。

【问题讨论】:

  • 通常将for...in 用于数组是不好的做法。它更适合用于对象迭代。尝试使用普通的 for 循环
  • to.toLowerCase() 应该是 toLowerCase() 除非我弄错了。
  • 发布你的整个代码
  • 我认为这是电子邮件的to 属性。
  • This is very similar to your last question。这个答案没有解决什么问题?

标签: javascript arrays loops if-statement


【解决方案1】:
for (var i=0;i<emailList.length;i++) {
    for (var j=0;j<ignoreList.length;j++) {
        if (emailList[i].toLowerCase() != ignoreList[j]) //or whatever logic you're trying to pull off here
    }
}

这将迭代两个数组,检查每个可能的电子邮件组合以忽略,您可以通过这种方式使用更简单的 if 语句

【讨论】:

    【解决方案2】:

    试试这个:

    for (var i = 0; i < emailList.length; i++){ 
        if (ignoreList.indexOf(emailList[i].toLowerCase()) !== -1)
            // Your code to deal with the ignored email here
    }
    

    旧版浏览器没有用于数组的 indexOf,因此您可能需要添加此原型:

    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (obj, start) {
            for (var i = (start || 0), j = this.length; i < j; i++) {
                if (this[i] === obj) { return i; }
            }
            return -1;
        };
    }
    

    【讨论】:

    • 你为什么会返回true?当然,OP 想要处理所有电子邮件,而不仅仅是在发现第一个忽略时停止
    • 这只是表明该电子邮件在忽略列表中。我不知道他是否想在函数中使用此代码,或者只是在那里处理有问题的电子邮件。他可以简单地删除返回并插入他的代码
    【解决方案3】:

    您在if 子句中滥用了in。参见例如MDN docs for in

    语法:对象名称中的道具

    道具
    表示属性名称的字符串或数字表达式或 数组索引。

    而您正尝试在['some@example.com', 'some1@example.com'] 中检查some@example.com,而这始终是false

    【讨论】:

      【解决方案4】:

      如果您可以使用 Underscore.js,这非常简单,没有 in 的所有陷阱或 for 的样板:

      _.each( emailList, function( email ) {
        if ( !_.contains( ignoreList, email ) ) {
          // ...
        }
      });
      

      如果您可以更改您的数据,这样emailList 的格式与ignoreList (一个简单的电子邮件地址字符串数组)相同,那就更好了:

      _.each( _.difference( emailList, ignoreList ), function( email ) {
        // ...
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-12
        • 2011-09-30
        • 2014-01-20
        • 2016-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多