Sir*_*ton 50 javascript arrays jquery 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);
});
});
Run Code Online (Sandbox Code Playgroud)
现在我的问题是我的for循环中并没有删除所有项目.如果我例如典型的"这是一个测试""是"被删除,"a"停留. 的jsfiddle
我认为问题是for循环,因为如果我用splice删除一个项目,数组的索引会改变,所以它继续使用"错误"索引.
也许有人可以帮帮我吗?
Ian*_*Ian 134
您可以使用以下内容向后循环:
var searchInput, i;
searchInput = ["this", "is", "a", "test"];
i = searchInput.length;
while (i--) {
if (searchInput[i].length < 4) {
searchInput.splice(i, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
演示: http ://jsfiddle.net/KXMeR/
这是因为通过数组递增迭代,当你拼接它时,数组被修改到位,所以项目被"移位",你最终跳过了一些迭代.向后循环(带有一个while
或甚至一个for
循环)可以解决这个问题,因为你没有在你拼接的方向上循环.
同时,生成新阵列通常更快,而不是修改一个阵列.这是一个例子:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
其中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);
});
Run Code Online (Sandbox Code Playgroud)
演示: http ://jsfiddle.net/qky7D/
参考文献:
Array.prototype.filter
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filterArray.prototype.filter
浏览器支持 - http://kangax.github.io/es5-compat-table/#Array.prototype.filter如果你安装了lodash库,他们有一个你可能想要考虑的甜蜜宝石。
该函数是_.forEachRight (从右到左迭代集合的元素)
这是一个例子。
var searchInput = ["this", "is", "a", "test"];
_.forEachRight(searchInput, function(value, key) {
if (value.length < 4) {
searchInput.splice(key, 1);
}
});
Run Code Online (Sandbox Code Playgroud)
var myArr = [0,1,2,3,4,5,6];
Run Code Online (Sandbox Code Playgroud)
问题陈述:
myArr.splice(2,1);
\\ [0, 1, 3, 4, 5, 6];
Run Code Online (Sandbox Code Playgroud)
现在3在第二个位置移动,长度减少1,这就产生了问题.
解决方案:一个简单的解决方案是在拼接时反向迭代.
var i = myArr.length;
while (i--) {
// do your stuff
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
51573 次 |
最近记录: |