JavaScript按字符数过滤值的数组(JavaScript filtering an array of values by character count)

编程入门 行业动态 更新时间:2024-10-25 14:32:10
JavaScript按字符数过滤值的数组(JavaScript filtering an array of values by character count)

这应该是一个快速的,但我抓我的头,为什么这一点的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; });

更多推荐

本文发布于:2023-07-23 18:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235721.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符   filtering   JavaScript   character

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!