簡體   English   中英

通過循環將值分配給數組索引

[英]Assign value to array indexes through loop

我正在努力尋找將循環函數應用於數組的方法,希望您能為我提供幫助。 我有一個組列表,我想自動將人員請求分配到組,並將這些請求分配到有空缺的區域。
因此,即時通訊看着我會得到一個表:
第1組| NB人
第2組| NB人
第3組| NB人
等等...

因此,我知道我需要一個“如果”條件來檢查比較人員請求與每個組中的空缺,然后如果組中的空缺高於預訂請求,則將其分配。
我知道如何使用array.push函數將保留變量添加到數組中,但是我正在努力循環並分配給包含2列的數組...

    <label for="groups">Reservation request (1-10):</label>
    <div id="reservation">
    <input type="number" name="form" id="number" min="1" max='10'>
    <br><br>
    <button onclick="groups()">Submit</button>
    </div>



 var myArray = ["Group 1", "Group 2", "Group 3"];
 function groups(){
 form = number.value;
 if (form >=1){  
     for (var i; i<myArray.length; i++) {
         if (myArray[i] > form){
             myArray[i] = form;
             console.log(myArray);
         }
         else {alert("no");}

你能幫我嗎?

非常感謝Marion

如果我正確理解您的意思,您想做的是:

  • 從一些空組開始,這些空組在添加人員時可以成長,但永遠不會超過10個成員
  • 根據要求(按下按鈕)將任意數量的人添加到第一組,該組可以容納所有請求的成員
  • 如果沒有群組可以容納所有請求的成員,請添加新群組並將請求添加到該群組。

假設這樣做,最簡單的方法是不使用多維數組(“兩列數組”):

var myArray = [0,0,0];

function groups() {
    var form = document.getElementById('number').value;
    if (form >=1) {  
        for (var i; i<myArray.length; i++) {
            if (myArray[i] < 10 - form) {
                myArray[i] += form;
                return;
            }
        }
        myArray.push(form); // this will only happen if "return" up there never happened
    }
    else {alert("no");
}

如果要使用組名/多維數組,可以這樣進行:

var myArray = [['Group 0',0], ['Group 1',0], ['Group 2',0]];

function groups() {
    var form = document.getElementById('number').value;
    if (form >=1) {  
        for (var i; i<myArray.length; i++) {
            if (myArray[i][1] < 10 - form) { // myArray[i][1] is the number of reservations in group i, myArray[i][0] would be the group's name
                myArray[i][1] += form;
                return;
            }
        }
        myArray.push(['Group ' + myArray.length, form); // this will only happen if "return" up there never happened
    }
    else {alert("no");
}

為了獲得更好的可讀性,可以在myArray中使用結構化對象,而不是使用更多數組:

var myArray = [{name:'Group 0',reserved:0}, {name:'Group 1',reserved:0}, {name:'Group 2',reserved:0}];

function groups() {
    var form = document.getElementById('number').value;
    if (form >=1) {  
        for (var i; i<myArray.length; i++) {
            if (myArray[i].reserved < 10 - form) { // myArray[i].reserved is the number of reservations in group i, myArray[i].name would be the group's name
                myArray[i].reserved += form;
                return;
            }
        }
        myArray.push({name:'Group ' + myArray.length, reserved:form); // this will only happen if "return" up there never happened
    }
    else {alert("no");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM