感谢@axtck对Fisher Yates随机化的帮助,他帮助我在这里将数字改为单词:
由于shuffle函数会对数组索引进行shuffle,所以您可以像在数组中添加名称字符串一样对数组进行shuffile。
代码现在显示了一个单词字符串,单词之间用逗号分隔,效果很好!
现在我想用空格替换逗号(例如: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()
将返回数组的字符串表示形式,即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>