用空格替换逗号? Fisher-Yates 随机化

Replace commas with spaces ? Fisher-Yates randomization

感谢 @axtck 对 Fisher Yates 随机化的帮助,他帮我把这里的数字变成了文字 :

代码现在显示一串单词,单词之间用逗号分隔,效果很好!

现在我想用空格替换逗号(例如:Histoire Chien Koala Arbre Italique Lampadaire Docteur Boulet Maison Forge Gagnant Ennui)

谁能帮我把这些逗号改成空格?

谢谢

   // replace numbers with names   
const inputArray = ["Arbre", "Boulet", "Chien", "Docteur", "Ennui", "Forge", "Gagnant", "Histoire", "Italique", "Koala", "Lampadaire", "Maison"];


//define Fisher-Yates shuffle
const fisherShuffle = function(array) {
  let currentIndex = array.length,
    temporaryValue,
    randomIndex;

  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  document.getElementById("fyresults").append(array.toString());
};

fisherShuffle(inputArray);
<p><span id="fyresults"></span></p>

在数组上调用 toString() 将 return 数组的字符串表示形式,即 item1,item2,....

如果你想以另一种方式加入数组,你可以使用数组方法join(),它需要一个分隔符字符串,在你的例子中是space join(" ") .

一些例子:

const testArr = ["first", "second", "..."]; // example array

const arrString = testArr.toString(); // calling toString() on it
const arrJoinedX = testArr.join("X"); // joining by X
const arrJoinedSpace = testArr.join(" "); // joining by space

// logging
console.log("Array:", testArr);
console.log("Array toString():", arrString);
console.log("Array joined with X:", arrJoinedX);
console.log("Array joined with space:", arrJoinedSpace);

所以要将此应用于您的示例,您可以这样做:

// replace numbers with names   
const inputArray = ["Arbre", "Boulet", "Chien", "Docteur", "Ennui", "Forge", "Gagnant", "Histoire", "Italique", "Koala", "Lampadaire", "Maison"];


//define Fisher-Yates shuffle
const fisherShuffle = function(array) {
  let currentIndex = array.length,
    temporaryValue,
    randomIndex;

  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  
  const joinedBySpace = array.join(" "); // join by space
  document.getElementById("fyresults").append(joinedBySpace); // append to element
};

fisherShuffle(inputArray);
<p><span id="fyresults"></span></p>