Computer >> Máy Tính >  >> Lập trình >> Javascript

Làm cách nào để tìm các phần tử của mảng JavaScript theo nhiều giá trị?


Sau đây là đoạn mã để tìm các phần tử của mảng JavaScript theo nhiều giá trị -

Ví dụ

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

Đầu ra

Đoạn mã trên sẽ tạo ra kết quả sau -

Làm cách nào để tìm các phần tử của mảng JavaScript theo nhiều giá trị?

Khi nhấp vào nút 'BẤM VÀO ĐÂY' -

Làm cách nào để tìm các phần tử của mảng JavaScript theo nhiều giá trị?