我有這樣一個初級的Javascript編碼挑戰,我必須生成隨機字符,用戶選擇寬度和高度,而 "隨機 "是指隨機字符在回圈中出現的次數,正如我所理解的。
使所有的值都可以由用戶調整
我知道這個解決方案非常簡單,但我似乎無法達到這個目的。這是我目前的代碼:
<script type="text/javascript"/span>>
let width = prompt("Choose a Width value")。
let height = prompt ("Choose a height value") 。
let random = prompt ("選擇一個隨機值");
let string = "";
for(let i = 0; i < height; i ) {
for(j = 0; j < width; j ) {
string = "#"/span>。
}
string = "<br>"。
}
const characters = '*'/span>;
function generateRandomCode(){
let result = ""/span>
let charactersLength = characters.length;
for (let i = 0; i < random ; i ) {
result = characters.charAt(Math. floor(Math.random() * charactersLength))。
}
return result
}
document.write(string)。
</script>
有沒有人知道如何生成這些隨機字符,并讓用戶選擇它的次數? 謝謝你 <3
uj5u.com熱心網友回復:
字串是不可變的。用一個2d陣列可能更容易。
。document. getElementById("calc").onclick = () => {
const width = document.getElementById("width"/span>).value。
const height = document.getElementById("height").value。
const random = document.getElementById("隨機").value。
//創建2D陣列,用'#'填充。
var arr = Array. from({length: height}, () => Array. from({length: width}, () => '#') )。
//在陣列中以隨機索引替換。
let replaced = 0;
while ( replaced < random) {
const x = Math.floor(Math.random()* height)。
const y = Math.floor(Math.random()* width)。
if (arr[x][y] !=='*'/span>) {
arr[x][y] = '*'/span>;
replaced = 1;
}
}
//轉換為字串; }
let result = arr.join('<br/> ')。 replaceAll(',','') 。
//顯示結果。
document.getElementById("result") 。 innerHTML = `<pre>${result}</pre> `;
};
<div>
<label for="width">/span>Width: </label>
< input type="number" id="width" value="5" />
</div>
<div>/span>
<label for="height">/span>Height。 </label>Height: </label>
< input type="number" id="height" value="5" />
</div>
<div>/span>
<label for="隨機">/span>隨機。 </label>隨機: </label>
< input type="number" id="隨機" value="5" />
</div>
<div>/span>
<button id="calc"/span>> 去</按鈕>
</div>/span>
<div id="result">/span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/309967.html
標籤:

