【问题标题】:Iterating through an array inside a conditional && statement in javaScript?遍历javaScript中条件&&语句中的数组?
【发布时间】:2019-06-02 14:22:21
【问题描述】:

我有一个数组:

console.log(tenantArray)
(8) ["WeWork", "Regus", "Spaces", "Knotel", "RocketSpace", "HQ Global Workspaces", "Other", "Select All"]

我还有一个大数据对象,我想使用 d3 过滤它,使用一个复选框。过滤器将基于两个条件,“Agency_Bro”属性,以及“Tenant”属性是否与上面列出的tenantArray 中的任何字符串匹配。从这个意义上说,上面的“tenantArray”数组只是一个用于字符串匹配目的的虚拟数组。过滤器必须满足这两个条件。

过滤器工作正常,如果它只是读取:

d3.selectAll("#JLLCheckbox").on("change", function() {

            var type = "JLL"            
            display = this.checked ? "inline" : "none";
            d3.selectAll(".features")
            .filter(function(d) { 
                return d.properties.Agency_Bro === type             
            })
            .attr("display", display);
});

但是,当我尝试添加两个条件语句时,复选框停止工作(未过滤数据)但没有出现错误消息。

d3.selectAll("#JLLCheckbox").on("change", function() {

    var type = "JLL"            
    display = this.checked ? "inline" : "none";

    d3.selectAll(".features")
        .filter(function(d) { 
            return d.properties.Agency_Bro === type &&
                    tenantArray.forEach(function(entry) {
                    if (d.properties.Tenant === entry){
                        return d.properties.Tenant
                    }
                    });         
        })
});

两个问题:上述逻辑失败的原因是什么?而且,有没有更有效的方法来做到这一点,而无需经历阵列的麻烦?提前致谢!

【问题讨论】:

  • forEach 原型不返回任何内容,但您将其用作过滤器内条件的一部分,我很确定 && undefined 的任何内容都会返回 false

标签: javascript arrays d3.js checkbox


【解决方案1】:

改成这样,你可以在你的数组上使用indexOf()来查看值是否包含在里面,如果不包含则返回false:

return d.properties.Agency_Bro === type &&
   tenantArray.indexOf(d.properties.Tenant) > -1; //Does a boolean check if indexOf() 
   //returns a value greater than -1, which means the value was found in your array
});

indexOfhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf 的文档

【讨论】:

  • @RyanWilson,感谢您的帮助!您的回答也很有帮助,我计划进一步测试这两种方法。
  • 再检查一遍。
【解决方案2】:

您最好将forEach 替换为some 方法以接收true/false 值:

d3.selectAll("#JLLCheckbox").on("change", function() {

  var type = "JLL"
  display = this.checked ? "inline" : "none";

  d3.selectAll(".features")
    .filter(function(d) {
      return d.properties.Agency_Bro === type &&
        tenantArray.some(function(entry) {
          return d.properties.Tenant === entry;
        });
    })
});

【讨论】:

  • 非常感谢!它现在正在工作。但是有一个问题:在这种情况下,'some' 方法到底在做什么?
  • @DiamondJoe12,乐于助人。 some() 方法测试数组中的至少一个元素是否通过了提供的函数实现的测试。在这种情况下,测试是d.properties.Tenant === entry。
  • 太棒了。这正是我正在寻找的,但不知道 some() 方法的存在。再次感谢。
  • @DiamondJoe12 我不知道你为什么要这样做,因为indexOf() 也能正常工作并减少代码量,但嘿,这是你的选择。
  • @RyanWilson,可能是因为在您的示例中entry 是undefined?
猜你喜欢
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多