javascript - 在 javaScript 的条件 && 语句中迭代数组?

标签 javascript arrays d3.js checkbox

我有一个数组:

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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

关于javascript - 在 javaScript 的条件 && 语句中迭代数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54082536/

相关文章:

javascript - 获取此 contenteditable 元素中的当前行和行索引?

python - 如何在不使用 Pandas 的情况下更改列的位置

javascript - 在 while 循环 D3 中更新参数

javascript - d3 桑基图中的排序节点

javascript - d3 鼠标事件返回元素

javascript 中的 php 计数器不起作用

javascript - COLORREF 转 RGB

javascript - 内联网络 worker : Uncaught SyntaxError: Unexpected identifier

ios - 难以理解数组追加

java - 如何在 android studio 中使用我的应用程序在字符串数组中添加更多字符串