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

Phương thức array.flatMap() trong JavaScript

flatMap() kết hợp map() và flat(), làm phẳng mảng lồng nhau sau khi biến đổi.

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 {       font-size: 20px;       font-weight: 500;    } </style> </head> <body> <h1>Array.flatMap() trong JavaScript</h1> <div class="sample"></div> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3> Nhấn nút để chuyển mảng lồng thành mảng phẳng </h3> <script>    let fillEle = document.querySelector(".sample");    let arr = ["cow", ["bull", "lion", "tiger"], "sheep"];    for (x of arr.entries()) {       fillEle.innerHTML += x + "<br>";    }    document.querySelector(".Btn").addEventListener("click", () => {       arr = arr.flatMap((x) => x);       fillEle.innerHTML = "";       for (x of arr.entries()) {          fillEle.innerHTML += x + "<br>";       }    }); </script> </body> </html>

Kết quả

Mảng lồng ["cow", ["bull","lion","tiger"], "sheep"] thành ["cow","bull","lion","tiger","sheep"].