美文网首页
JS:数组排列组合

JS:数组排列组合

作者: limengzhe | 来源:发表于2021-11-02 18:07 被阅读0次

    JS:数组排列组合

    1. 原数组

      const source = [
        ['black', 'white', 'red', 'blue'],
        ['128GB', '256GB', '512GB'],
        ['zhengzhou', 'shenzhen', 'vietnam'],
      ]
      
    2. 方法

      let temp = []
      let results = []
      
      function combine(arr, index = 0) {
        arr[index].forEach(item => {
          temp[index] = item
      
          index + 1 < arr.length
            ? combine(arr, index + 1)
            : results.push(temp.slice())
        })
      }
      
    3. 执行

      combine(source)
      
      console.log(results)
      
    4. 输出

      [
        [ 'black', '128GB', 'zhengzhou' ],
        [ 'black', '128GB', 'shenzhen' ],
        [ 'black', '128GB', 'vietnam' ],
        [ 'black', '256GB', 'zhengzhou' ],
        [ 'black', '256GB', 'shenzhen' ],
        [ 'black', '256GB', 'vietnam' ],
        [ 'black', '512GB', 'zhengzhou' ],
        [ 'black', '512GB', 'shenzhen' ],
        [ 'black', '512GB', 'vietnam' ],
        [ 'white', '128GB', 'zhengzhou' ],
        [ 'white', '128GB', 'shenzhen' ],
        [ 'white', '128GB', 'vietnam' ],
        [ 'white', '256GB', 'zhengzhou' ],
        [ 'white', '256GB', 'shenzhen' ],
        [ 'white', '256GB', 'vietnam' ],
        [ 'white', '512GB', 'zhengzhou' ],
        [ 'white', '512GB', 'shenzhen' ],
        [ 'white', '512GB', 'vietnam' ],
        [ 'red', '128GB', 'zhengzhou' ],
        [ 'red', '128GB', 'shenzhen' ],
        [ 'red', '128GB', 'vietnam' ],
        [ 'red', '256GB', 'zhengzhou' ],
        [ 'red', '256GB', 'shenzhen' ],
        [ 'red', '256GB', 'vietnam' ],
        [ 'red', '512GB', 'zhengzhou' ],
        [ 'red', '512GB', 'vietnam' ],
        [ 'blue', '128GB', 'zhengzhou' ],
        [ 'blue', '128GB', 'shenzhen' ],
        [ 'blue', '128GB', 'vietnam' ],
        [ 'blue', '256GB', 'zhengzhou' ],
        [ 'blue', '256GB', 'shenzhen' ],
        [ 'blue', '256GB', 'vietnam' ],
        [ 'blue', '512GB', 'zhengzhou' ],
        [ 'blue', '512GB', 'shenzhen' ],
        [ 'blue', '512GB', 'vietnam' ]
      ]
      

    相关文章

      网友评论

          本文标题:JS:数组排列组合

          本文链接:https://www.haomeiwen.com/subject/wxlfzltx.html