如何将一个数组中的每个元素与其他元素一次显示,而不是一次显示?
例如:
var myArray:any = "a b c d"
然后显示:
a,b
a,c
a,d
b,a
b,c
b,d
等
答案 0 :(得分:3)
in for in可以正常工作。
var myArray = "a b c d".split(' ');
for (let first of myArray) {
for (let second of myArray) {
if (first !== second) {
console.log(`${first},${second}`)
}
}
}
答案 1 :(得分:0)
尝试
function f (arr) {
arr.forEach(function(e) {
arr.forEach(function(e2) {
if (e === e2) return;
var str = e + "," + e2;
// print str
});
});
}
f("a b c d".split(' '));
答案 2 :(得分:0)
您也可以像这样使用dankogai/js-combinatorics:
cmb = Combinatorics.combination(['a','b','c','d'], 2);
while(a = cmb.next()) console.log(a);
// ["a", "b"]
// ["a", "c"]
// ["a", "d"]
// ["b", "c"]
// ["b", "d"]
// ["c", "d"]
答案 3 :(得分:0)
"a b c d".split(' ').map((el, idx, arr)=>{
let elIdx = arr.indexOf(el);
let rest = arr.slice(0,elIdx).concat(arr.slice(elIdx+1)).map((l)=> console.log(`${el},${l}`) );
});
答案 4 :(得分:0)
为此,您可以简化地图功能,但必须使用数组
这里是一个例子:
const myArray = ["a", "b", "c", "d", "e", "f", "g"]
// forEach accept one first param x current value
// second param is optional xi index of value
// third param is optional too and it refer the array itself
myArray.forEach( (x, xi, myArr) => {
myArr.forEach( (y, yi) => {
if(xi !== yi) { console.log(`${x}, ${y}`); }
});
});