如何在 JavaScript 中獲取所有陣列的各種組合?
您可以使用您自己的函式來獲取所有組合。
示例
以下是程式碼 −
function combination(values) { function * combinationRepeat(size, v) { if (size) for (var chr of values) yield * combinationRepeat(size - 1, v + chr); else yield v; } return [...combinationRepeat(values.length, "")]; } var output = combination([4,5]); console.log(output);
要執行上述程式,您需要使用以下命令 −
node fileName.js.
這裡,我的檔名是 demo306.js。
輸出
這將生成以下輸出 −
PS C:\Users\Amit\javascript-code> node demo306.js [ '44', '45', '54', '55' ]
廣告