如何通过多个值查找 JavaScript 数组中的元素?


以下是通过多个值来查找 JavaScript 数组元素的代码 −

示例

 实时演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Find elements of JavaScript array by multiple values</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to see if arr contains all elements of arr1 or not</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let arr = [11, 44, 22, 16, 25, 91, 58];
   let arr1 = [22, 91, 11];
   let contain = arr1.every((item) => arr.includes(item));
   BtnEle.addEventListener("click", () => {
      if (contain) resEle.innerHTML = "The arr contains all elements of arr1";
      else resEle.innerHTML = "The arr doesn't contain all elements of arr1";
   });
</script>
</body>
</html>

输出

上面的代码会产生以下输出 −

点击“点击此处”按钮 −

更新于: 18-Jul-2020

241 次浏览

启动你的 职业生涯

完成课程获得认证

开始吧
广告