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

Toán tử Spread JavaScript

Toán tử trải rộng JavaScript cho phép chúng ta mở rộng một mảng thành các phần tử mảng riêng lẻ. Để sử dụng toán tử spread, ba dấu chấm (…) phải được đặt trước tên mảng.

Sau đây là mã cho toán tử lây lan JavaScript -

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;
   }
   .sample,
   .result {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
   .result {
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>JavaScript Spread Operator</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button combine the two arrays using spread operator
into a new one
</h3>
<script>
   let resultEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   let arr1 = [1, 2, 3, 4, 5];
   let arr2 = ["A", "B", "C", "D", "E"];
   sampleEle.innerHTML = "arr1 = " + arr1 + "<br> arr2 = " + arr2;
   document.querySelector(".Btn").addEventListener("click", () => {
      let arr3 = [...arr1, ...arr2];
      resultEle.innerHTML = "arr3 = " + arr3;
   });
</script>
</body>
</html>

Đầu ra

Toán tử Spread JavaScript

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

Toán tử Spread JavaScript