这应该是一个快速的,但我抓我的头,为什么这一点的JavaScript不适合我。 目标是获取输入框的值(用空格分隔的字符串),将这些单词列为数组中的项目,并删除少于3个字符的项目:
var typed = $('input').val(); var query = typed.split(" "); var i=0; for (i=0; i<query.length; i++) { if (query[i].length < 3) { query.splice(i,1); } }有这个运行onkeyup为输入框,它似乎工作,但只有大约50%的时间(字符串的1和2个字符在某种程度上有时进入阵列)。 任何建议将非常感激。
This should be a quickie, but I'm scratching my head as to why this bit of JavaScript isn't working for me. The goal is to take the value of an input box (string of words separated by spaces), list these words as items in an array, and remove those which are fewer than 3 characters:
var typed = $('input').val(); var query = typed.split(" "); var i=0; for (i=0; i<query.length; i++) { if (query[i].length < 3) { query.splice(i,1); } }Have this running onkeyup for the input box and it seems to work, but only about 50% of the time (strings of 1 and 2 characters somehow find their way into the array on occasion). Any suggestions would be hugely appreciated.
最满意答案
问题在于你在移除元素的同时迭代。 考虑这个数组:
["he", "l", "lo world"]最初你的循环从索引0开始,并从数组中删除"he" 。 现在新阵列是
["l", "lo world"]在下一次迭代中, i将是1 ,并且您将检查"lo world"的长度,从而完全忽略"l"字符串。
使用Array中的filter方法删除不需要的元素。
var biggerWords = query.filter(function(word) { return word.length >= 3; });The problem is that you are iterating while removing the elements. Consider this array:
["he", "l", "lo world"]Initially your loop starts at index 0 and removes "he" from the array. Now the new array is
["l", "lo world"]In the next iteration i will be 1, and you will check "lo world"'s length, thus ignoring the "l" string altogether.
Use the filter method in Array to remove the unwanted elements.
var biggerWords = query.filter(function(word) { return word.length >= 3; });更多推荐
发布评论