Как объединить массив с другим разделителем в JavaScript? - PullRequest
0 голосов
/ 18 июня 2020

var array = ["Red", "Green", "White", "Black", "Gray"];
document.write(array.join("+"));

Я хочу, чтобы он выводился так: Red+Green-White*Black#Gray

Ответы [ 3 ]

2 голосов
/ 18 июня 2020

Вы можете сделать что-то вроде этого:

// your initial array of elements to join
var array = ["Red", "Green", "White", "Black", "Gray"];

// new list of separators to use
var separators = ["+","-","*","#"];

var joined = array.reduce((output, elem, index) => {
  // always join the next element
  output += elem;

  // add next separator, if we're not at the final element in the array
  if (index < array.length - 1) output += separators[index];

  // return the current edits
  return output;
}, '')

console.log(joined)
1 голос
/ 18 июня 2020

Вы можете уменьшить, взяв массив для glue.

var array = ["Red", "Green", "White", "Black", "Gray"],
    glue = ['+', '-', '*', '#'],
    result = array.reduce((a, b, i) => [a, b].join(glue[(i - 1) % glue.length]));

console.log(result);
0 голосов
/ 18 июня 2020

Предполагается, что разделители случайны и не содержат logi c. Вы можете взглянуть на следующий код:

var chars = ['a', 'b', 'c', 'd'];
var delimitters = ['+', '-', '*', '#'];

function customJoin(resultantStr, num) {
    let delimitter = delimitters[Math.floor(Math.random()*delimitters.length)];
  return resultantStr+delimitter+num;
}

console.log(chars.reduce(customJoin))

Дайте мне знать, если это будет полезно для вас! Удачного кодирования!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...