如何用JavaScript/jQuery扁平化数组

如何用JavaScript/jQuery扁平化数组

JavaScript包含许多数组(或称二维数组),任务是将数组扁平化,使其看起来像一维JavaScript数组。有两种方法,将在下面讨论。你也可以使用Underscore.js .flatten()的例子。

方法1:使用Array.prototype.concat.apply()方法来执行操作。使用concat()apply()方法将数组连接成1维数组。

  • 示例:
<!DOCTYPE HTML>
<html>
  
<head>
    <title>
        How to flatten array with
        the JavaScript?
    </title>
      
    <style>
        body {
            text-align: center;
        }
          
        h1 {
            color: green;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
      
    <p id="GFG_UP"></p>
      
    <button onClick="GFG_Fun()">
        click here
    </button>
      
    <p id="GFG_DOWN"></p>
      
    <script>
        var up = document.getElementById('GFG_UP');
        var down = document.getElementById('GFG_DOWN');
        var arr1 = [1, 2, 3];
        var arr2 = [4, 5, 6, 7];
        var arr = [arr1, arr2, 8, 9];
          
        up.innerHTML = "Click on button to get "
                + "the common elements from these"
                + " array <br>Array -[[" + arr[0]
                + "], [" + arr[1] + "], " + arr[2]
                + ", " + arr[3] + "]";
  
        function GFG_Fun() {
            down.innerHTML = 
                Array.prototype.concat.apply([], arr);
        }
    </script>
</body>
  
</html>
  • 输出:
    如何用JavaScript/jQuery扁平化数组?

方法2: jQuery中的$.map()方法可以用来执行操作。这个方法需要数组和一个方法作为输入。第二个参数是一个方法,它将原数组中的元素逐一取出并返回其元素。

  • 示例:
<!DOCTYPE HTML>
<html>
  
<head>
    <title>
        How to flatten array with
        the JavaScript?
    </title>
      
    <style>
        body {
            text-align: center;
        }
          
        h1 {
            color: green;
        }
    </style>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
    </script>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
      
    <p id="GFG_UP"></p>
      
    <button onClick="GFG_Fun()">
        click here
    </button>
      
    <p id="GFG_DOWN"></p>
      
    <script>
        var up = document.getElementById('GFG_UP');
        var down = document.getElementById('GFG_DOWN');
        var arr1 = [1, 2, 3];
        var arr2 = [4, 5, 6, 7];
        var arr = [arr1, arr2, 8, 9];
          
        up.innerHTML = "Click on button to get the"
                + " common elements from these array"
                + "<br>Array - [[" + arr[0] + "], ["
                + arr[1] + "], " + arr[2] + ", " 
                + arr[3] + "]";
  
        function GFG_Fun() {
            down.innerHTML = $.map(arr, function(n) {
                return n;
            });
        }
    </script>
</body>
  
</html>
  • 输出:
    如何用JavaScript/jQuery扁平化数组?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程