我想将一个单词拆分成字母放入数组并随机显示字母。我遇到了麻烦。用两个相同字母的单词。并且还显示了正确的字母数量,但并未显示所有字母。
这是我的代码我是一个菜鸟:
window.onload = init;
function init() {
//var name=prompt("what is your name ? ","");
//character(name) ;
words();
}
function character(name) {
var name = name;
document.getElementById("words").innerHTML = "hey " + name + " my name is koala could you help me put these words back in order?";
}
function words() {
var lastlet = "";
var words = ["joe", "suzy", "terry", "fox", "lopez"];
var rand = Math.floor(Math.random() * words.length) + 0;
//for one word and seperation with letters
var ranwor = words[rand].split("");
for (var i = 0; i < ranwor.length; i++) {
var inn = ranwor[Math.floor(Math.random() * ranwor.length)].split().shift();
if (true) {
var di = document.getElementById("wor").innerHTML += inn;
}
lastlet = inn;
}
}
&#13;
#char {
height: 65px;
width: 65px;
}
#words {
height: 100px;
width: 200px;
}
&#13;
<img id="char" src="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg" />
<p id="words"></p>
<br>
<p id="wor"></p>
<p id="wo"></p>
<br>
<textarea id="inp"></textarea>
<br>
<button>
I think this is right :)
</button>
&#13;
答案 0 :(得分:1)
只需使用随机数对数组进行排序,然后使用join(),这样就不需要循环了。
var words = ["joe", "suzy", "terry", "fox", "lopez"];
var rand = words[Math.floor(Math.random() * words.length)];
function scramble (word, rescrambled) {
var scrambled = word.split("").sort(function(){ return Math.random() > .5 ? 1 : -1; }).join("");
if (word===scrambled && !rescrambled) { //if it matches the original, retry once
return scramble (word, true);
}
return scrambled;
}
console.log("Random word: ", scramble(rand));
console.group("loop them");
while(words.length){
var x = words.pop();
console.log(x,":", scramble(x));
}
console.groupEnd("loop them");
&#13;