javascript - 使用 for 循环中的拼接从数组中删除项目

标签 javascript jquery arrays for-loop

<分区>

我想实现一种 jQuery 实时搜索。 但是在将输入发送到服务器之前,我想删除我的数组中所有具有 3 个或更少字符的项目(因为在德语中,这些词通常可以在搜索方面被忽略) 所以 ["this", "is", "a", "test"] 变成了 ["this", "test"]

$(document).ready(function() {
var timer, searchInput;
$('#searchFAQ').keyup(function() {
    clearTimeout(timer);
    timer = setTimeout(function() {
        searchInput = $('#searchFAQ').val().match(/\w+/g);
        if(searchInput) {
            for (var elem in searchInput) {
                if (searchInput[elem].length < 4) {
                    //remove those entries
                    searchInput.splice(elem, 1);
                }
            }
            $('#output').text(searchInput);
            //ajax call here
        }
    }, 500);
});
});

现在我的问题是并不是所有项目都在我的 for 循环中被删除。 例如,如果我输入“这是一个测试”"is"被删除,“a”会保留下来。 JSFIDDLE

我认为问题出在 for 循环上,因为如果我删除带有拼接的项目,数组的索引会发生变化,因此它会继续使用“错误”索引。

也许有人可以帮助我吗?

最佳答案

方案一

你可以向后循环,像下面这样:

var searchInput, i;

searchInput = ["this", "is", "a", "test"];
i = searchInput.length;
while (i--) {
    if (searchInput[i].length < 4) {
        searchInput.splice(i, 1);
    }
}

演示: http://jsfiddle.net/KXMeR/

这是因为递增地迭代数组,当你拼接它时,数组被修改到位,所以项目被“移动”并且你最终跳过了一些迭代。向后循环(使用 while 甚至 for 循环)可以解决这个问题,因为您没有按照拼接的方向循环。


解决方案2

与此同时,生成新数组通常比就地修改数组更快。这是一个例子:

var searchInput, newSearchInput, i, j, cur;

searchInput = ["this", "is", "a", "test"];
newSearchInput = [];
for (i = 0, j = searchInput.length; i < j; i++) {
    cur = searchInput[i];
    if (cur.length > 3) {
        newSearchInput.push(cur);
    }
}

其中 newSearchInput 将只包含有效长度的项目,并且您在 searchInput 中仍然有原始项目。

演示: http://jsfiddle.net/RYAx2/


方案三

除了上面的第二个解决方案之外,一个类似的、更新的Array.prototype 方法可以更好地处理这个问题:filter。这是一个例子:

var searchInput, newSearchInput;

searchInput = ["this", "is", "a", "test"];
newSearchInput = searchInput.filter(function (value, index, array) {
    return (value.length > 3);
});

演示: http://jsfiddle.net/qky7D/


引用资料:

关于javascript - 使用 for 循环中的拼接从数组中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16217333/

相关文章:

javascript - 通过更改 Selector 重用代码

python - 检查 python 中两个数组中的反向对重复

javascript - 如何将一种方法连接到不同的对象?

javascript - (Laravel) 预取数据库数据中的实时搜索

javascript - 奇怪的 ng-model 行为(ng-model 映射到数组元素)

javascript - 从列中删除过滤器

javascript - 如何制作真正的响应式图像 slider ?

jQuery ajax 错误回调未触发

javascript - 如何遍历 JavaScript 数组?

javascript - JavaScript 中的 Highchart 系列更新