檢查使用者輸入的字串是否在 JavaScript 陣列中


我們需要編寫一個 JavaScript 程式,向用戶提供一個輸入字串值。

然後,該程式應該檢查輸入值是否與一些硬編碼陣列值匹配。如果輸入字串值包含在陣列中,則我們的程式應該在螢幕上列印 true,否則列印 false。

示例

該程式碼如下所示:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width">
   <title>CHECK EXISTENCE</title>
</head>
<body>
   <script>
      const arr = ['arsenal', 'chelsea', 'everton', 'fulham',
      'swansea'];
      const checkExistence = () => {
         const userInput = document.getElementById("input").value;
         const exists = arr.includes(userInput);
         document.getElementById('result').innerText = exists;
      };
   </script>
   <input type="text" id="input">
   <button onclick="checkExistence()">Check</button>
   <p id='result'></p>
</body>
</html>

輸出

螢幕上輸出的內容如下:

更新日期:2020 年 11 月 20 日

415 次瀏覽

開啟你的 職業生涯

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.