use case1:
Input:['aa','bb','cc'],['dd','ee']
Output:["aadd", "aaee", "bbdd", "bbee", "ccdd", "ccee"]
use case2:
Input:['aa','bb','cc'],['dd','ee'],['ff','gg','hh']
Output:["aaddff", "aaddgg", "aaddhh", "aaeeff", "aaeegg", "aaeehh", "bbddff", "bbddgg", "bbddhh", "bbeeff", "bbeegg", "bbeehh", "ccddff", "ccddgg", "ccddhh", "cceeff", "cceegg", "cceehh"]
输入参数不定
方式 1 大概 250 - 300ms:
var mergeArr = (...args) => {
const mergeString = (a,b) => {
var s = '';
for (var i = 0 , len = b.length; i < len; i++){
if(i !== 0) s += ',';
s += a.join(b[i] + ',') + b[i];
}
var arr = s.split(',');
return arr;
}
var arrs = Array.apply(null, args);
var arrData = arrs[0];
for (var i = 1,len = arrs.length ; i < len; i++)
arrData = mergeString(arrData,arrs[i]);
// console.log(arrData);
};
方式 2 180 - 250 ms
function all() {
var pro = ''
for (var i = 0; i < arguments.length; i++) {
var obj = JSON.stringify(arguments[i]);
if(i !== arguments.length-1){
pro = pro + `
var outArr = []
function p${i}(str) {
for (var i = 0; i < ${obj}.length; i++) {
var obj = str + ${obj}[i];
p${i+1}(obj)
}
};`
}else{
pro = pro + `
function p${i}(str) {
for (var i = 0; i < ${obj}.length; i++) {
var obj = str + ${obj}[i];
outArr.push(obj)
}
};
p0('')
console.log(outArr)
`
eval(pro)
}
}
}
测试数据:
var time = new Date().getTime();
// mergeArr(['aa','bb','cc'],['dd'],['ee','ff']);
mergeArr(['aa','bb','cc'],['dd','ee'],['ff','gg','hh'],['dd','ee'],['ff','gg','hh'],['dd','ee'],['ff','gg','hh'],['dd','ee'],['ff','gg','hh'],['dd','ee'],['ff','gg','hh'],['ff','gg','hh'],['dd','ee'],['ff','gg','hh']);
console.log(new Date().getTime() - time);
还有更好的办法吗?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.