我有3个不同的数组,长度相同
var title = ['title 1','title 2','title 3'];
var description = ['description 1','description 2','description 3'];
var link = ['link 1','link 2','link 3'];
如何将所有数组值合并到一个带有管道的单个数组中 - |
- delimiter?
结果:
final_arr = [
'title 1|description 1|link 1',
'title 2|description 2|link 2',
'title 3|description 3|link '
]
尝试
title.map((x,i) => `${x}|${description[i]}|${link[i]}`);
我们在这里使用标准的js'工具'和良好的文档:arrow function,map和template literals以及每个数组具有相同数量元素的事实
var title = ['title 1','title 2','title 3'];
var description = ['description 1','description 2','description 3'];
var link = ['link 1','link 2','link 3'];
var r = title.map((x,i) => `${x}|${description[i]}|${link[i]}`);
console.log(r);
听起来像课堂作业...... :)
var A=[];
for(var i=0; i<title.length; i++){
A.push(title[i]+'|'+description[i]+'|'+link[i]);
}
这是一个很好的基本解决方案,你的老师不能拒绝!
与Array#map
一起使用。基于索引匹配
var title = ['title 1','title 2','title 3'];
var description = ['description 1','description 2','description 3'];
var link = ['link 1','link 2','link 3'];
var res= title.map((a,b)=> a+'|'+description[b]+'|'+link[b]);
console.log(res)
或Array#ForEach
var title = ['title 1','title 2','title 3'];
var description = ['description 1','description 2','description 3'];
var link = ['link 1','link 2','link 3'];
var res =[];
title.forEach((a,b)=> res.push(a+'|'+description[b]+'|'+link[b]));
console.log(res)
你可以减少数组。
const
title = ['title 1', 'title 2', 'title 3'],
description = ['description 1', 'description 2', 'description 3'],
link = ['link 1', 'link 2', 'link 3'],
result = [title, description, link].reduce((a, b) => a.map((v, i) => v + '|' + b[i]));
console.log(result);