我剛開始使用 JS,我正在嘗試從陣列中獲取隨機元素。數量由用戶的輸入決定,我認為這部分有效。這些函式由按鈕的 onClick 呼叫。搜索互聯網給了我下面最好的解決方案,但即使在 console.log 中,我也無法使獲取元素的部分作業。
我在控制臺中實際看到的是一個長度為:0 的空陣列 []
我的代碼有什么問題?這是我在論壇上經常看到的方法,人們說它對他們有用,而且它基本上是相同的代碼,但單詞改變了。
userArray = [];
function addElement(){
let element = document.getElementById("add-input").value;
userArray.push(element);
document.getElementById("add-input").value = "";
}
function getElements(){
let amount = document.getElementById("amount-input").value;
newList = [];
for(i=0; i<amount.value; i ){
randomElement = userArray[Math.floor(Math.random() * userArray.length)];
newList.push(randomElement);
}
console.log(newList);
}
<div class="phase-add">
<p class="label-p">Input an element</p>
<div class="input-box">
<input class="add-input" type="text" name="add-input" id="add-input">
<button class="add-btn" onclick="addElement()">Add</button>
</div>
</div>
<div class="phase-get">
<div class="input-box">
<p class="label-p">Choose the amount</p>
<input type="text" name="amount-input" id="amount-input">
</div>
<button onclick="getElements()">Get elements</button>
</div>
uj5u.com熱心網友回復:
變數amount已經是一個字串/數字。您無需在 for 回圈中再次獲取它的值。更改為for(i=0; i<amount; i ){in for 回圈將解決此問題。
userArray = [];
function addElement(){
let element = document.getElementById("add-input").value;
userArray.push(element);
document.getElementById("add-input").value = "";
}
function getElements(){
let amount = document.getElementById("amount-input").value;
console.log(amount)
newList = [];
for(i=0; i<amount; i ){
randomElement = userArray[Math.floor(Math.random() * userArray.length)];
newList.push(randomElement);
}
console.log(newList);
}
<input id = "add-input" type = "text" ></input>
<button onclick = "addElement()">Add Element</button>
<input id = "amount-input" type = "number"></input>
<button onclick = "getElements()">Get Elements</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/458889.html
標籤:javascript 数组
