[英]Recursive search through and object in JavaScript
我正在嘗試在對象內進行遞歸搜索,並且我正在嘗試根據某些條件查找所有匹配項。 我使用以下功能:
function checkForTitleMatch(query, node) {
var results = [];
if (node.attr.title.indexOf(query) != -1) {
results.push = node;
}
for (var i = 0; i < node.children.length; i++) {
checkForTitleMatch(query, node.children[i]);
}
return results;
}
我不認為匹配中存在問題等等 - 我認為問題在於我在遞歸中返回結果的方式。
在我的情況下,結果總是一個空數組,因為第一個/根元素將永遠不匹配(在我的情況下)並且子迭代的結果未正確返回,imho。
有人可以請你糾正我或指出必須改變什么才能得到正確的結果嗎?
你有兩個問題:
(1) results.push = node;
它應該是results.push(node)
。
(2)每次調用checkForTitleMatch
都會創建自己的results
數組,並且數組永遠不會聚合。
解決此問題的一種可能方法:
function checkForTitleMatch(query, node) {
var results = [];
(function check(node) {
if (node.attr.title.indexOf(query) != -1) {
results.push(node);
}
for (var i = 0; i < node.children.length; i++) {
check(node.children[i]);
}
})(node);
return results;
}
即使清楚/更快也會使用屬性選擇器 ,例如
node.querySelectorAll('*[title*=' + query + ']');
雖然這不查詢頂級節點node
,但假設query
沒有“特殊字符”。
值得注意的是,通過使用Array.concat
合並結果,您可以在沒有閉包的情況下解決此問題:
function checkForTitleMatch(query, node){
var results = [];
if (node.attr.title.indexOf(query) != -1){
results.push(node);
}
for (var i=0; i<node.children.length; i++){
results = Array.prototype.concat.apply(results,
checkForTitleMatch(query, node.children[i])
);
}
return results;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.