简体   繁体   English

使用分隔符将成对相邻的数组元素相互连接

[英]Join pairwise adjacent array elements to each other with a delimiter

I have an array我有一个数组

var array=["kiran", "1998", "roshan", "1997", "Vidyut", "2004", "mahesh", "2005"];

I have to combine it and make is like我必须把它结合起来,就像

combined=["kiran-1998","roshan-1997","Vidyut-2004","mahesh-2005"];

I have to combine the array[n] with array[n+1] with '-' in between.我必须将array[n]array[n+1]组合起来,中间有'-'。 How can I do that in JavaScript?我怎样才能在 JavaScript 中做到这一点?

I have tried .join("-") method in it but it joins the whole array, but I don't know how to join only two of them我已经在其中尝试了.join("-")方法,但它连接了整个数组,但我不知道如何只连接其中的两个

I tried this for loop code also but it also shows error我也试过这个 for 循环代码,但它也显示错误

for(i=0;i<array.length;i=i+2)
{
    updateArray[i] = array[i].join("-");
}

I was trying to join first element and second element but got stuck here我试图加入第一个元素和第二个元素,但被困在这里

UPDATE: Based on OP's EDIT.更新:基于 OP 的编辑。

SOLUTION-1:解决方案 1:

 var array=["kiran", "1998", "roshan", "1997", "Vidyut", "2004", "mahesh", "2005"]; const updatedArray = []; for(i=0;i<array.length;i=i+2) { updatedArray.push(`${array[i]}-${array[i+1]}`); } console.log(updatedArray);

SOLUTION-2:解决方案 2:

You can use ES6 map and filter to achieve this: Try this:)您可以使用 ES6 mapfilter来实现此目的:试试这个:)

 var array=["kiran", "1998", "roshan", "1997", "Vidyut", "2004", "mahesh", "2005"]; const updatedArray = array.map((item,index,arr)=>{ if(index%2 === 0){ return `${item}-${arr[index+1]}`; } }).filter(item=>item;==undefined). console;log(updatedArray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM