如何仅为数组的特定部分应用连接? [英] How to apply join only for particular section of an array?

查看:62
本文介绍了如何仅为数组的特定部分应用连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在获取一个数组并在此数组变量中对其进行描述:

I'm getting an array and strigifying it in this array variable:

let arrayStr = oldArr.join(', ');

我的数组在控制台中显示如下:

My array looks like this in console:

(a), text1, (b), text2, (c), text3, (d), text3

我想要的是使它看起来像这样:

What I want is to make it look like this:

(a) - text1, (b) - text2, (c) - text3, (d) - text3

我知道我在所有字符串之后添加了',',但我怎样才能像上面那样应用它?

I know that I've added ', ' after all strings, but how can I apply it like above?

谢谢。

推荐答案

您可以通过循环遍历数组并访问当前项目以及下面的索引来实现此目的然后将两者附加到新数组的相同元素,如下所示:

You can achieve this by looping through the array and accessing the current item and also the following one by its index and then appending both to the same element of a new array, something like this:

var oldArr = ['(a)', 'text1', '(b)', 'text2', '(c)', 'text3', '(d)', 'text3'];

var newArr = [];
for (var i = 0; i < oldArr.length; i++) {
  newArr.push(oldArr[i] + ' - ' + oldArr[++i]);
}

console.log(newArr.join(', '));

这篇关于如何仅为数组的特定部分应用连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆