繁体   English   中英

遍历JavaScript中条件&&语句内的数组?

[英]Iterating through an array inside a conditional && statement in javaScript?

我有一个数组:

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
                    }
                    });         
        })
});

两个问题:以上逻辑失败的任何原因? 而且,有没有更有效的方法来执行此操作,而不会遇到阵列的麻烦? 提前致谢!

更改为此,您可以在数组上使用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
});

indexOf文档https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

您最好用some方法替换forEach以接收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;
        });
    })
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM