问题描述
感谢 @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()
将返回数组的字符串表示形式,即 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>