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

我想实现一种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循环中被删除。例如,如果我删除打字“这是一个测试”“是”,则“ a”保持不变。 JSFIDDLE


我认为问题是for循环,因为如果我删除带有拼接的项,则数组的索引会更改,因此它会继续使用“错误的”索引。


也许有人可以帮助我吗?


繁华开满天机
浏览 441回答 3
3回答

慕村225694

var myArr = [0,1,2,3,4,5,6];问题陈述:myArr.splice(2,1);&nbsp; \\ [0, 1, 3, 4, 5, 6];现在3个动作在第二个位置移动,长度减少1个,从而造成问题。解决方案:一个简单的解决方案是在拼接时以相反的方向进行迭代。var i = myArr.length;while (i--) {&nbsp; &nbsp; // do your stuff}

慕娘9325324

如果您安装了lodash库,则可能要考虑它们。函数是_.forEachRight (从右到左迭代集合的元素)这是一个例子。var searchInput = ["this", "is", "a", "test"];_.forEachRight(searchInput, function(value, key) {&nbsp; &nbsp; if (value.length < 4) {&nbsp; &nbsp; &nbsp; &nbsp; searchInput.splice(key, 1);&nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP