2015-12-31 34 views
-1

我想將一個單詞拆分爲字母並將其放入數組中並隨機顯示字母。我有麻煩。用同一個字母的兩倍的單詞。並且正在顯示正確的字母數量,但並非所有字母都正在顯示。我如何在一個數組中隨機顯示所有項目

這裏是我的代碼,我是小白:

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; 
 
    } 
 
}
#char { 
 
    height: 65px; 
 
    width: 65px; 
 
} 
 

 
#words { 
 
    height: 100px; 
 
    width: 200px; 
 
}
<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>

+0

您是選擇從「ranwor」隨機字母不說它們不能被選擇一次以上。所以它會在每個單詞的每個字母中尋找一個隨機字母。當選擇「喬」時,沒有什麼能夠阻止它選擇「j」三次。 –

+0

@Valdorous所以我想做什麼? – benji8

+1

'「applesauce」.split(「」)。sort(function(){return Math.random()> .5?1:-1;})。join(「」)' – epascarello

回答

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");

相關問題