Home > Article > Web Front-end > Searching for a Value in an Array Using JavaScript.
This program demonstrates how to search for a specific val within an array using a while loop in JavaScript. The user is prompted to enter a value, and the program then checks if this value exists in a predefined variety. If the value is found, a message indicating its availability is displayed; otherwise, a message indicating its absence is shown.
Simple Example:
let Val = prompt("Enter Value ..!"); let numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300]; let i = 0; let Find = false; while (i < numbers.length) { if (numbers[i] == Val) { Find = true; break; } i++; } if (Find) { console.log("Available Variable..!"); } else { console.log("No Available Variable..!"); }
Output:
100 This Variable Available in the Array..!
Finding an Element in an Array Using DOM in JavaScript:
In this program, we demonstrate how to search for a specific value within an array using a while loop in JavaScript. The user enters a value in an input field, and the program checks if this value exists in a predefined array. If the value is found, a message indicating its availability is displayed; otherwise, a message indicating its absence is shown.
Example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Find Element in Array Using DOM in JavaScript </title> <style> body { font-family: Arial, sans-serif; margin: 20px; } h4, h2 { color: #333; } input { padding: 10px; margin-right: 10px; border: 1px solid #ccc; border-radius: 5px; } button { padding: 10px 20px; border: none; border-radius: 5px; background-color: #28a745; color: white; cursor: pointer; } button:hover { background-color: #218838; } </style> </head> <body> <h4>Find Element in Array</h4> <h4 id="NumData"></h4> <input type="text" placeholder="Enter Value" id="Num" /> <button onclick="SearchEle()">Find</button> <h2 id="Ans"></h2> <script> let Data = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300]; document.getElementById("NumData").innerHTML += "Our Array is: " + Data.join(', '); function SearchEle() { let NewValue = document.getElementById("Num").value; let i = 0; let Find = false; while (i < Data.length) { if (Data[i] == NewValue) { Find = true; break; } i++; } if (Find) { document.getElementById("Ans").innerHTML = `${NewValue} is Available..!`; } else { document.getElementById("Ans").innerHTML = `${NewValue} is not Available..!`; } } </script> </body> </html>
Output:
The above is the detailed content of Searching for a Value in an Array Using JavaScript.. For more information, please follow other related articles on the PHP Chinese website!