我想知道如何以這種方式合并陣列,例如:
const names = ['MARCUS', 'LUCAS', 'ANDREA']
const surnames = ['SMITH', 'JOHNSON', 'WILLIAMS']
[...merge stuff]
// and then the output should be
const full_names = ['MARCUS SMITH', 'LUCAS JOHNSON', 'ANDREA WILLIAMS']
uj5u.com熱心網友回復:
這是幾種方法。假設兩個輸入陣列中的名字和姓氏是 1:1 匹配的。
const names = ['MARCUS', 'LUCAS', 'ANDREA']
const surnames = ['SMITH', 'JOHNSON', 'WILLIAMS']
// way 1: traditional loop
const res = [];
for (let i = 0; i < names.length; i ) {
res.push(`${names[i]} ${surnames[i]}`);
};
console.log('full_names: ', res);
// way 2: another way - more functional flavor
const res2 = names.reduce((acc, e, i) => {
acc.push(`${e} ${surnames[i]}`);
return acc;
}, [])
console.log('full_names: ', res2);
輸出:
[ 'MARCUS SMITH', 'LUCAS JOHNSON', 'ANDREA WILLIAMS' ]
uj5u.com熱心網友回復:
這里一個 zip 函式創建一個陣列[["MARCUS","SMITH"],["LUCAS","JOHNSON"],["ANDREA","WILLIAMS"]],然后 map 將內部陣列轉換為字串。
const names = ['MARCUS', 'LUCAS', 'ANDREA'];
const surnames = ['SMITH', 'JOHNSON', 'WILLIAMS'];
const zip = (...arrays) => {
let res = [];
for(let i = 0; i < arrays[0].length; i ) {
res.push([]);
for(let j = 0; j < arrays.length; j ) {
res[i].push(arrays[j][i]);
}
}
return res;
};
const res = zip(names, surnames)
.map(([name, surname]) => name ' ' surname);
console.log(res);
uj5u.com熱心網友回復:
你可以這樣做:
const names = ['MARCUS', 'LUCAS', 'ANDREA']
const surnames = ['SMITH', 'JOHNSON', 'WILLIAMS']
const result = names.map((n, i) => `${n} ${surnames[i]}`)
document.getElementById('app').innerText = JSON.stringify(result)
<pre id="app"></pre>
uj5u.com熱心網友回復:
您可以按如下方式使用遞回:
const names = ['MARCUS', 'LUCAS', 'ANDREA'],
surnames = ['SMITH', 'JOHNSON', 'WILLIAMS'],
fn = (n,sn,i,f) =>
i <= n.length - 1 ?
fn(n,sn,i 1,[...f,`${n[i]} ${sn[i]}`]) :
f;
console.log( fn(names,surnames,0,[]) );
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/467425.html
標籤:javascript 数组 合并
