檢查使用者輸入的字串是否在 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>輸出
螢幕上輸出的內容如下:

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP