如何将两个数组组合为笛卡尔积? [英] How to combine two arrays as a cartesian product?
本文介绍了如何将两个数组组合为笛卡尔积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有
array1 = [1,2,3,4,5];
array2 = ["one","two","three","four","five"];
我想得到array3
,其中array1
的所有元素都带有array2
的第一个(和其他)元素,等等.
I want to get array3
where all elements of array1
with first (and others) element of array2
and etc.
例如:
array3 = ["one 1", "two 1", "three 1", "four 1", "five 1", "one 2", "two 2", "three 2", "four 2", "five 2"...]
我知道我需要使用for循环,但是我不知道该怎么做.
I understand that I need to use for loop but I don't know how to do it.
推荐答案
您可以使用两个for循环:
You can use two for-loops:
var array1 = [1,2,3,4,5];
var array2 = ["one","two","three","four","five"];
var array3 = [];
for (var i = 0; i < array1.length; i++) {
for (var j = 0; j < array2.length; j++) {
array3.push(array2[j] + ' ' + array1[i]);
}
}
console.log(array3);
这篇关于如何将两个数组组合为笛卡尔积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文