Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Toán tửSpread (Spread Operator) trong JavaScript


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

Dưới đây là mã cho toán tử spread trong 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>

Kết quả

Toán tửSpread (Spread Operator) trong JavaScript

Khi nhấn nút 'CLICK HERE':

Toán tửSpread (Spread Operator) trong JavaScript