0
votes

Comment rejoindre un tableau avec un séparateur différent en JavaScript?

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


1 commentaires

Vous pouvez le faire avec un Réduire la méthode .


3 Réponses :


2
votes

Vous pouvez faire quelque chose comme ceci:

p>

// 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)


0 commentaires

1
votes

Vous pouvez réduire en prenant une matrice pour colle code>.

p>

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);


3 commentaires

(i => (a, b) => [a, b] .join (séparateurs [++ i, i% = séparateurs.length])) (- 1) peut simplement être (a, b, i) => [a, b] .join (séparateurs [i]) ;)


@Vlaz, l'index commence par un.


Vous avez raison! Désolé, j'ai raté ça. Mais alors c'est [i-1] au lieu de [i] . J'apprécie le style de régime ici, cependant.



0
votes

En supposant que les délimiteurs soient aléatoires et ne contiennent aucune logique. Vous pouvez consulter le code suivant:

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

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

console.log(chars.reduce(customJoin))


0 commentaires