慕桂英3389331
2022-10-27 14:10:39
我正在嘗試在 JavaScript 中創(chuàng)建一個(gè)函數(shù),給定一個(gè)字符串將返回一個(gè)包含所有名稱組合的數(shù)組,例如。 Name As per ITD - Potter Harry James Potter Harry Harry Potter Harry James Potter下面的代碼也給出了組合,但以這種方式: Name As per ITD - Potter Harry Potter James Potter Potter Harry James Harry James Harry James 代碼 :var PanName = "Harry James Potter";var ret = PanName.split(" ").reduce(function(ret, el, i, arr) { var n = arr.slice(++i); [2, 3].forEach(function(c) { ret = ret.concat(n.map(function(_, i) { return [el].concat(n.slice(i)).slice(0, c).join(' '); })); }); if (i === arr.length - 1) ret.pop(); return ret;}, []);var arr = ret.toString().split(",");arr = arr.map(function(el) { return el.trim();});arr = arr.filter(function(item, index, inputArray) { return inputArray.indexOf(item) == index;});var i;var text1 = "";for (i = 0; i < arr.length; i++) { text1 += arr[i] + "<br>";}$('#displayCombinationNames').html(text1);<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><p id="displayCombinationNames"></p>誰能幫我得到下面的輸出:預(yù)期輸出:Name As per ITD - Potter Harry James
Potter Harry
Harry Potter
Harry James Potter
1 回答

幕布斯7119047
TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以通過將只有名字和姓氏的名稱分別處理更長(zhǎng)的情況來做到這一點(diǎn)。對(duì)于第一種情況,結(jié)果只是一個(gè)first last和的數(shù)組last first。對(duì)于后一種情況,結(jié)果包括這些值,但也包括第一個(gè)后面的中間名:
var PanName = "Harry James Potter";
var arr = PanName.split(' ');
var ret;
if (arr.length == 2) {
ret = [arr.join(' '), arr.reverse().join(' ')];
} else {
ret = [arr.join(' ')];
first = arr.shift();
last = arr.pop();
ret.push([first, last].join(' '), [last, first].join(' '));
ret.push([last, first, arr].join(' '));
}
console.log(ret);
添加回答
舉報(bào)
0/150
提交
取消