首页 > 解决方案 > 测试字符串是否包含字符串数组中的单词

问题描述

它不起作用。它总是与其他。我需要使用数组,并查看字符串是否包含数组中的任何单词。请帮忙,这真的很烦人

function buttonClick() {
  var name = document.getElementById('myText').value;
  var yourstring = name;
  var substrings = ['fruit', 'apple'];
  var length = substrings.length;
  while (length--) {
    if (yourstring.indexOf(substrings[length]) != -1) {
      var outcome = 1;
    } else {
      var outcome = 2;
    }
  }
  switch (outcome) {
    case 1:
      document.getElementById('fruitvalue').innerHTML = name + 'is ...';
      break;
    case 2:
      document.getElementById('fruitvalue').innerHTML = name + 'is not ...';
      break;
  }
}
<body>
  <center>
    Last Name:<input type="text" id="myText" value="">
    <button 
      onClick="buttonClick()" 
      style="font-family:font; color:blue;"
    >Submit</button>
    <h2 id="fruitvalue"></h2>
  </center>
</body>
</head>

标签: javascripthtml

解决方案


我建议您取消循环和 ifs,并通过使用array.someString.prototype.includes显着减少代码。这段代码可以清楚地写成一行:

    function hasWord(str, words) {
      return words.some(word => str.includes(word));
    }

    const name = document.getElementById('myText').value;
    const substrings = ['fruit', 'apple'];
    const element = document.getElementById('fruitvalue');
    
    function buttonClick() {
      const matches = hasWord(name, substrings);    
      const suffix = matches ? 'is ...' : 'is not ...';
      element.innerHTML = `${name} ${suffix}`;
    }
    <body>
      <center>
        Last Name:
        <input type="text" id="myText" value="">
        <button 
          onClick="buttonClick()" 
          style="font-family:font; color:blue;"
        >Submit</button>
        <h2 id="fruitvalue"></h2>
      </center>
    </body>


推荐阅读