簡體   English   中英

從一個數組(包含嵌套數組)中選擇 x 個隨機元素,並且每個嵌套數組中不超過一個

[英]Select x random elements from an array (that contains nested arrays) and no more than one from each nested array

我是編程新手,但已經學習了足夠的 HTML 和 CSS 來創建我的手工博客onlyrss.org ,現在我已經嘗試了我的第一個 JavaScript“應用程序” 該應用程序完成了我需要它執行的大部分操作,即從數組中選擇 x 個隨機練習。 但是,有些練習是“替代品”,我不想在輸出中超過一個,例如環形引體向上或單杠引體向上、或引體向上、500m 行或 250m 行等。

我的猜測是我的數組中需要嵌套數組,將備選方案組合在一起,然后代碼只從每個嵌套數組中選擇 1 個選項(猜測如果主數組中的每個條目都是嵌套數組,即使它只是現在只有一個值嗎?)。 坦率地說,這遠遠超出了我目前的能力,因此我請求幫助。

這是Codepen 上代碼的鏈接,但代碼也顯示在下面:

// get the slider value
    function getNumber(){
        let input = document.getElementById("userInput").value;
      return input
    }

//triggered by the main button: set the number of exercises to "n"
    function myFunction() {
    let n = getNumber() 

//clear the list of any existing exercises
    document.getElementById("todays_exercises").innerHTML = "";

//define the array
    let all_exercises = [ 
      " air squats ×40",
      " skip ×200",
      " burpees ×20",
      " row 500m",
      " pull-ups ×10",
      " finger board pull-ups ×10",
      " ring pull-ups ×10",
      " sit-ups ×40",
      " press-ups ×25",
      " lunges ×20",
      " curls ×15",
      " ring rows ×12",
      " assisted ring dips ×10",
      " ring push ups ×10",
      " power snatch ×10",
      " power clean ×20",
      " power clean & jerk ×15",
      " hanging leg raises ×20",
      " bench press ×10",
      " calf raises ×20",
      " plank 20s",
      " dips ×20",
      " row 250m"
    ];

//Set the max value of the slider (with id=userInput) to the # of elements in the array
    document.getElementById("userInput").setAttribute('max', all_exercises.length);

// shuffle the full array
    function shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j],  array[i]];
        }
    }

// pull out the first n values from the shuffled array and display as ordered list
    shuffleArray(all_exercises);
    all_exercises.slice(0,n).forEach(e => {
        todays_exercises.innerHTML =  todays_exercises.innerHTML + '<li>' + e + '</li>' ;
    });
    }

任何幫助將非常感激。

嵌套數組可以解決問題。 您也可以使用 shuffle 函數對嵌套數組進行隨機播放。

// similar exercises are grouped
const all_exercises = [
    ["pull-ups","bar-pullup"],
    ["power-snatch","power-clean"],
]


all_exercises.slice(0,n).forEach(e => {
    shuffleArray(e); // shuffle the nested array
    // choose the first element using e[0]
    todays_exercises.innerHTML =  todays_exercises.innerHTML + '<li>' + e[0] 
     + '</li>' ;
});
}

這是一個工作的codepen。

暫無
暫無

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

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