1

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

由于 shuffle 函数对数组索引进行了随机播放,因此您可以像以前一样对数组进行随机播放,但在数组中添加名称字符串。

代码现在显示一串用逗号分隔的单词,它运行良好!

现在我想用空格替换逗号(例如: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>

4

1 回答 1

1

调用toString()数组将返回数组的字符串表示,即item1,item2,...

如果你想以另一种方式加入数组,你可以使用数组方法join(),它需要一个分隔符字符串,在你的情况下是一个空格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>

于 2021-06-09T07:57:41.287 回答