Javascript-如何连接两个不同大小的数组的字符串值?
2018-01-23
281
我有两个数组,例如:
数组 1:
arr1 = ["Precon", "Contra", "Postco", "Cancel", "Consul"]
数组 2:
arr2 = ["EJID", "EMBA", "EMPR", "GOBI", "PART", "PPOL", "SACI", "SOFL", "SOFM", "0000", "", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "011", "0110", "9999"]
我想从上述两个数组生成一个新数组,将数组 1 中的每个项目递归地连接成新项目,以获得最终的数组,如下所示:
final = ['Precon-EJID', 'Contra-EJID', 'Postco-EJID', 'Cancel-EJID', 'Consul-EJID', 'Precon-EMBA', 'Contra-EMBA', 'Postco-EMBA', 'Cancel-EMBA', 'Consul-EMBA', 'Precon-EMPR', 'Contra-EMPR', 'Postco-EMPR', 'Cancel-EMPR', 'Consul-EMPR'...etc]
提前谢谢您
3个回答
您可以使用 2 个简单的
for of
循环来实现此目的:
var arr1 = ["Precon", "Contra", "Postco", "Cancel", "Consul"];
var arr2 = ["EJID", "EMBA", "EMPR", "GOBI", "PART", "PPOL", "SACI", "SOFL", "SOFM", "0000", "", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "011", "0110", "9999"]
var finalArr = [];
for ( var item2 of arr2 ) {
for ( var item1 of arr1 ) {
finalArr.push(`${item1}-${item2}`);
}
}
console.log(finalArr);
Blue
2018-01-23
您可以使用嵌套的 Array#map 调用,并使用 Array#concat 展平结果:
const arr1 = ["Precon", "Contra", "Postco", "Cancel", "Consul"]
const arr2 = ["EJID", "EMBA", "EMPR", "GOBI", "PART", "PPOL", "SACI", "SOFL", "SOFM", "0000", "", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "011", "0110", "9999"]
const result = [].concat(...arr2.map((s1) => arr1.map((s2) => `${s2}-${s1}`)))
console.log(result)
Ori Drori
2018-01-23
下面是执行此操作的一行代码:
arr1 = ["Precon", "Contra", "Postco", "Cancel", "Consul"]
arr2 = ["EJID", "EMBA", "EMPR", "GOBI", "PART", "PPOL", "SACI", "SOFL", "SOFM", "0000", "", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "011", "0110", "9999"]
const result = [].concat(...arr1.map(prefix => arr2.map(suffix => prefix+suffix)));
console.log(result)
// EDIT: if order matters, reverse the use of arr1 and arr2:
const orderedResult = [].concat(...arr2.map(suffix => arr1.map(prefix => prefix+suffix)));
console.log(orderedResult)
CRice
2018-01-23