繁体   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