首页 > 解决方案 > 如何使用本地存储在我的网页上保存随机结果(每次重新加载都会有所不同)?

问题描述

我制作了一个网站,您可以在其中生成随机锻炼,即包含 5 种随机锻炼和 5 种随机类型代表的锻炼。为了生成随机数量的代表,我对我制作的数组使用了 Math.floor(Math.random()。为了生成 5 种不同的随机锻炼,我使用 Javascript 中的 shuffle 函数在每次页面重新加载时随机播放我的数组。

现在我希望用户能够将他们在网页上获得的任何结果保存到他们计算机上的本地存储中,以便他们可以随时访问特定的随机锻炼。我该怎么办???

在这里,我发布了我为生成结果而创建的代码。

// This makes the reps generate randomly in a list of 5

let maxNr = 10;

function generateRep(){ 
  let randomReps = [`4x10`,`4x8`, `4x20`, `4x12`, `4x15`,`3x10`, `3x15`, `4x5`, `5x10`, `10x10`];
  for(let i=0; i < 5; i++){
  let randomNr = Math.floor(Math.random() * maxNr); 
  if (randomNr==9) maxNr=9;
  let repsText = "<li>"+randomReps[randomNr]+"</li>";
  document.getElementById("repsList").innerHTML+=repsText;
  console.log(maxNr);
 }
}

//THIS IS A SHUFFLE FUNCTION 

function shuffle(array) {
  let currentIndex = array.length,  randomIndex;
  // While there remain elements to shuffle...
  while (currentIndex != 0) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
  return array;
}

//This is the workout generator for, in this case, a chest and back workout using the shuffle function from above.

function generateWorkout() {
  let workoutList = [`Chins`, `Wide barbell row (bent over)`, `Row with machine`, `Cable pulldown`,
  `Lat pulldown`, `Bent-over dumbbell alternating row`,`Reverse fly with barbell`,`Push-ups`, 
  `Face-pull with cable`, `Seated face pull`, `Single arm lat pulldown`, `Low position row with cable`, 
  `Split stance high anchor row with cable`, `Bench Press`, `Overhead press with dumbbells or barbell`,
  ` One arm row with dumbbell`,` Inverted row`, `Close grip dumbbell press`, ];
  let shuffleWorkoutList= shuffle(workoutList);
  for(let i=0; i < 5; i++){
    let workoutText = "<li>"+workoutList[i]+"</li>";
    document.getElementById("listOfWorkouts").innerHTML+=workoutText;
  }
} ```

标签: javascriptarraysmathlocal-storageshuffle

解决方案


使用 LocalStorage 的语法是

  • 保存一个值:localStorage.setItem("name-or-key", "value")键和值应该是字符串。
  • 得到一个值:localStorage.getItem("name-or-key")

这就是你可以在你的代码片段中实现它的方式:

function generateWorkout() {
  let workoutList = [`Chins`, `Wide barbell row (bent over)`, `Row with machine`, `Cable pulldown`,
  `Lat pulldown`, `Bent-over dumbbell alternating row`,`Reverse fly with barbell`,`Push-ups`, 
  `Face-pull with cable`, `Seated face pull`, `Single arm lat pulldown`, `Low position row with cable`, 
  `Split stance high anchor row with cable`, `Bench Press`, `Overhead press with dumbbells or barbell`,
  ` One arm row with dumbbell`,` Inverted row`, `Close grip dumbbell press`, ];
  let shuffleWorkoutList= shuffle(workoutList);
  for(let i=0; i < 5; i++){
    let workoutText = "<li>"+workoutList[i]+"</li>";
  };
  localStorage.setItem("workout-list", workoutList.join(","));
};

function load_prev_workout() {
    const prev_workout = localStorage.getItem("workout-list").split(",");
    console.log(prev_workout);
    for(let i=0; i < 5; i++){
        let workoutText = "<li>"+prev_workout[i]+"</li>";
        console.log("Now use this:",workoutText,"for something.");
    };
};

然后有条件地调用这些:

if(localStorage.getItem("workout-list")) {
    load_prev_workout();
} else {
    generateWorkout();
};

如果您想一次保存多个锻炼,让用户为该锻炼选择一个名称,或者给它一个唯一的 ID,然后将其用作 localStorage 项目名称/键的一部分


推荐阅读