[英]How to rewrite loop to recursion
我实现了搜索功能,并按集合循环搜索。 在第一个迭代中,我需要按所有集合进行搜索,但所有下一个迭代都只能按第一个迭代的结果进行搜索。 我使用if语句if (i >= 1) collection = result;
这样做,但这并不安全,因为我需要保存集合。 是否可以将循环重写为递归函数? 我该如何使代码优雅?
var targets = target.split(' '); // => ['hello', 'world'];
for (var i = 0; i < targets.length; ++i) {
if (i >= 1) {
collection = result;
}
result = includes(collection, props, targets[i]);
}
我的搜索功能:
function includes(collection, props, target) {
var result = [];
var collection_length = collection.length;
var props_length = props.length;
var target_length = target.length;
for (var i = 0; i < collection_length; ++i) {
for (var j = 0; j < props_length; ++j) {
if (collection[i][props[j]]) {
if (collection[i][props[j]].toLowerCase().slice(0, target_length) === target) {
result.push(collection[i]);
continue;
}
}
}
}
return result.length !== 0 ? result : false;
}
var result = collection;
for (var i = 0; i < targets.length; ++i) {
result = includes(result, props, targets[i]);
}
也许我缺少了一些东西,但这不是您要尝试的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.