[英]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.