JavaScript 二维数组,如果输入 RegEx 匹配 col1 ,return col2

JavaScript 2D array, if input RegEx match col1 , return col2

我正在尝试设置一个聊天机器人,当用户输入匹配某个单词时,它会做出相应的响应。

这有效

  var input = "i love you";
  
  if(/.*cute.*/.test(input)) { alert("Aw.... so sweet");}
  if(/.*love.*/.test(input)) { alert("Love you too");}

//result "Love you too"

但是,如何将数据放入数组中并使其仍然有效?

示例:

var queryResponse = [ ["cute","Aw.... so sweet"],
                      ["love","Love you too"] ];

如何修改这一行?

 if(/.*  (what should i insert here?) .*/.test(input)) { alert(So that the response appear here?);}

你可以这样做:

var regexArray =  [ ["cute","Aw.... so sweet"],["love","Love you too"] ]
    
    for(var i = 0; i < regexArray.length ; i++){
    
    let re = new RegExp(`.*${regexArray[i][0]}*.`);

    if(re.test(input){
    alert(regexArray[i][1]);
    break;
     }
    }

每个键和值的索引应该匹配

var keys=['cute','love'];
var values= ['so cute', 'i love you'];
        
for(var i = 0; i < keys.length ; i++){
        
   let re = new RegExp(`.*${keys[i]}*.`);
    
   if(re.test(input){
        alert(values[i]);
        break;
   }
}

const queryResponseMap = new Map([
  ["cute", "Aw.... so sweet"],
  ["love", "Love you too"]
]);

function getResponse(query) {
  const iterator = queryResponseMap.entries();
  let result = iterator.next();

  while (!result.done) {
    const [key, val] = result.value;

    if (new RegExp(`.*${key}*.`).test(query)) {
      return val;
    }

    result = iterator.next();
  }

  return null;
}

console.log(getResponse("Hi love"));
console.log(getResponse("You're cute"));