Rumah  >  Soal Jawab  >  teks badan

Tutorial JavaScript: Cara membuat senarai menggunakan matriks

<p><strong>我有一个像这样的数组</strong></p> <pre class="brush:php;toolbar:false;">const input_array= [ ["hitam", "biru"], ["besar", "sederhana"], ["a", "b", "c"] //... adakah ia dinamik boleh ditambah banyak baris ];</pre> <p><strong>我该如何得到一个像这样的数组:</strong></p> <pre class="brush:php;toolbar:false;">const finallist = [ ["hitam", "besar", "a"], ["hitam", "besar", "b"], ["hitam", "besar", "c"], ["hitam", "sederhana", "a"], ["hitam", "sederhana", "b"], ["hitam", "sederhana", "c"], ["biru", "besar", "a"], ["biru", "besar", "b"], ["biru", "besar", "c"], ["biru", "sederhana", "a"], ["biru", "sederhana", "b"], ["biru", "sederhana", "c"], ]</pre> <p><strong>请记住input_array是动态的</strong></p> <p><strong>请告诉我如何做到这一点</strong></p>
P粉617237727P粉617237727432 hari yang lalu559

membalas semua(2)saya akan balas

  • P粉729518806

    P粉7295188062023-09-07 09:34:40

    Anda boleh melakukan sesuatu seperti ini:

    const input_array = [
        ["black", "blue"],
        ["large", "medium"],
        ["a", "b", "c"]
    ]
    const getCompinations = array =>
      array.reduce((v, b) =>
        v.reduce((r, g) => [...r, ...b.map(w => [].concat(g, w))], [])
      )
    console.log(getCompinations(input_array))
    

    balas
    0
  • P粉449281068

    P粉4492810682023-09-07 00:39:31

    Sila lihat ini, ia mungkin membantu:

    const input_array = [
        ["black", "blue"],
        ["large", "medium"],
        ["a", "b", "c"]
        //... 是否可以动态添加多行
    ];
    const mmc = input_array.reduce((e, r) => e * r.length, 1);
    const finallist = input_array.map((x,i)=>({index:i,arr:x})).reduce((e, r) => {
        for (var u = 0; u < mmc; u++) e[u] && (!r.arr.some(r => e[u].includes(r)) || e[u].length <= r.index) ? e[u].push(r.arr[u % r.arr.length]) : e.push([r.arr[u % r.arr.length]]);
        return e.sort(), e
    }, []);
    

    Berhati-hati! Boleh menyebabkan ranap penyemak imbas dalam matriks besar.

    balas
    0
  • Batalbalas