将匹配字符串的所有实例记录在一个数组中-JavaScript

Log all instances of a matched string in a array - JavaScript

本文关键字:一个 -JavaScript 数组 记录 字符串 实例      更新时间:2023-09-26

我有一个数组,我想找到在文本框上键入的匹配字符串的所有实例。

当前代码可用作fiddy-https://jsfiddle.net/Mithun6319/Lzmekhph/

var colors = ['Red', 'Blue', 'Black', 'Green', 'Grey'];
var boxHandeler = document.getElementById('box');
function textComplete(text) {
    boxHandeler.addEventListener('keyup', function (ev) {
       if (this.value.length >= 2) {
          var boxData = this.value;
          //console.log(boxData);
          for(i=0;i<colors.length;i++){
              while(colors[i].match(boxData)){
                  console.log[i];
              }
          }
       }
   });
}

如果你想要的话,是一个自动完成的文本框,正如你在评论中提到的那样。您可以使用datalist

<input list='colors' />
<datalist id="colors">
  <option value="Red">
  <option value="Blue">
  <option value="Black">
  <option value="Green">
  <option value="Grey">
</datalist>

您可以从下拉列表中选择,也可以键入您将看到过滤结果

以下是javascript的操作方法。这是您的代码的修改版本

<input type="text" id="box" onkeyup="matchThis(this.value)"/>
<script>
var colors = ['Red', 'Blue', 'Black', 'Green', 'Grey'];
var boxHandeler = document.getElementById('box');
function matchThis(value){
        if (value.length >= 2) {
            var boxData = value;
            //console.info("Search String "+boxData);           
            var pattern = new RegExp(boxData,'gi');
            for(i=0;i<colors.length;i++){               
                if(colors[i].match(pattern)){
                    console.warn(colors[i]);
                }               
            }
        }
}
</script>

你的代码有很多问题。首先,当找到匹配时,您正在调用无限循环(正如@ananth在评论中提到的)。您正试图以阵列的身份访问console.log

console.log[i];

代替

console.log(i);

由于某些原因,fiddle不起作用,所以请在实际环境中尝试它。