首页 > web前端 > js教程 > 正文

使用 JavaScript 在数组中搜索值。

WBOY
发布: 2024-07-29 14:21:10
原创
458 人浏览过

该程序演示了如何使用 JavaScript 中的 while 循环在数组中搜索特定的 val。系统会提示用户输入一个值,然后程序检查该值是否存在于预定义的变量中。如果找到该值,则会显示一条消息,指示其可用性;否则,会显示一条消息指示其不存在。

简单示例:

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..!");
}

登录后复制

输出:

100 This Variable Available in the Array..!
登录后复制

在 JavaScript 中使用 DOM 查找数组中的元素:
在此程序中,我们演示如何使用 JavaScript 中的 while 循环在数组中搜索特定值。用户在输入字段中输入一个值,程序检查该值是否存在于预定义的数组中。如果找到该值,则会显示一条消息,指示其可用性;否则,会显示一条消息指示其不存在。

示例:

<!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>

登录后复制

输出:

Image description

Image description

以上是使用 JavaScript 在数组中搜索值。的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!