JavaScript 中可以按橫線隔開的任一數量的陣列的笛卡爾積
我們需要編寫一個 JavaScript 函式,該函式可處理任意數量的字面量陣列。此函式應計算並返回所有元素的笛卡爾積陣列,並用短劃線('-')將它們隔開。
示例
程式碼如下 −
const arr1= [ 'a', 'b', 'c', 'd' ];
const arr2= [ '1', '2', '3' ];
const arr3= [ 'x', 'y', ];
const dotCartesian = (...arrs) => {
const res = arrs.reduce((acc, val) => {
let ret = [];
acc.map(obj => {
val.map(obj_1 => {
ret.push(obj + '−' + obj_1)
});
});
return ret;
});
return res;
};
console.log(dotCartesian(arr1, arr2, arr3));輸出
控制檯中的輸出如下 −
[ 'a−1−x', 'a−1−y', 'a−2−x', 'a−2−y', 'a−3−x', 'a−3−y', 'b−1−x', 'b−1−y', 'b−2−x', 'b−2−y', 'b−3−x', 'b−3−y', 'c−1−x', 'c−1−y', 'c−2−x', 'c−2−y', 'c−3−x', 'c−3−y', 'd−1−x', 'd−1−y', 'd−2−x', 'd−2−y', 'd−3−x', 'd−3−y' ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP