在遍历数组中的所有项目后重置随机化

问题描述 投票:0回答:3

我正在学习 JS,刚刚完成一个项目,代码如下:

const menu = {
    _meal: "",
    _price: 0,
    //Let set the new value of meal only if it's a string.
    set meal(mealToCheck) {
        if (typeof mealToCheck === "string") {
            return this._meal = mealToCheck;
        }
    },
    //Let set the new value of price only if it's a number.
    set price(priceToCheck) {
        if (typeof priceToCheck === "number") {
            return this._price = priceToCheck;
        }
    },
    //If both setters are true, then return a message using them, otherwise return message saying the values are wrong.
    get todaysSpecial() {
        if (this._meal && this._price) {
            return `Today's Special is ${this._meal}, for just ${this._price}£!!`;
        } else {
            return "Meal and Price wasn't entered correctly!!";
        }
    }
};

//Arrays for the meal options and respective prices, also a constant to get a random number in the array range.
const meals = ["Pizza", "Steak", "Pie", "Roast", "Moussaka", "Lasagne", "Tacos"];
const prices = [/*Pizza*/9, /*Steak*/13, /*Pie*/11, /*Roast*/14, /*Moussaka*/9, /*Lasagne*/10, /*Tacos*/9];
const random = Math.floor(Math.random() * meals.length);

//Assigns a new random value from the arrays. I used a single randomizer so that you can combine a plate to its price by the index number.
menu.meal = meals[random];
menu.price = prices[random];

//Check if the number of items in the meals and prices array it's equal, and if it is, creates the menu of the day string.
if (meals.length === prices.length) {
    console.log(menu.todaysSpecial);
} else {
    console.log("The number of prices and meals don't match!!");
}

在代码末尾,我添加了几个数组和一个

Math.random
,这样每次运行它时,它都会给我一个不同的值。

现在我正在尝试找到一种方法让随机值给出唯一值,直到达到数组长度,然后重新启动。目前,我的数组中有 7 个项目模拟一周中的某一天,我希望每个项目每周出现一次,然后重置。

我知道如何通过遵循数组索引顺序来做到这一点,但我无法想出一种随机执行的方法,任何输入?

javascript arrays random
3个回答
1
投票

您可以将价格和餐食组合起来,使其变得更简单,然后进行随机排列。

const menu = {
  _meal: "",
  _price: 0,
  //Let set the new value of meal only if it's a string.
  set meal(mealToCheck) {
    if (typeof mealToCheck === "string") {
      return (this._meal = mealToCheck);
    }
  },
  //Let set the new value of price only if it's a number.
  set price(priceToCheck) {
    if (typeof priceToCheck === "number") {
      return (this._price = priceToCheck);
    }
  },
  //If both setters are true, then return a message using them, otherwise return message saying the values are wrong.
  get todaysSpecial() {
    if (this._meal && this._price) {
      return `Today's Special is ${this._meal}, for just ${this._price}£!!`;
    } else {
      return "Meal and Price wasn't entered correctly!!";
    }
  }
};

//Arrays for the meal options and respective prices, also a constant to get a random number in the array range.
let meals = [
  { name: "Pizza", price: 9 },
  { name: "Steak", price: 13 },
  { name: "Pie", price: 11 },
  { name: "Roast", price: 14 },
  { name: "Moussaka", price: 9 },
  { name: "Lasagne", price: 10 },
  { name: "Tacos", price: 9 }
];

// Used to shuffle your meals array
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;
}

meals = shuffle(meals);

// Iterate meals
for (let i = 0; i < meals.length; i++) {
  menu.meal = meals[i].name;
  menu.price = meals[i].price;
  console.log(menu.todaysSpecial);
}

0
投票

每次从数组中选取值时很容易将其删除,当数组结束时只需将数组重置为初始值 为了没有兰特号的问题,它应该是这样的

Rand=Math.random()*array.lenght


0
投票

这就是我所做的。我没有创建新函数,而是更改了 TodaysSpecial 函数以接受数组,并从数组中随机选择一个元素。

const menu = {
  _meal: '',
  _price: 0,
  set meal (mealToCheck) {
    if(mealToCheck.length >= 1) {
    return this._meal= mealToCheck
    }
  },
  set price (priceToCheck ) {
    return this._price = priceToCheck  
  },
  get todaysSpecial () {
    let random = Math.floor(Math.random() * this._meal.length);
    if(this._meal && this._price) {
    return `Today’s Special is ${this._meal[random]} for $${this._price[random]}!`
    } else {
    return `Meal or price was not set correctly!`
    }
   },
 };

 menu.meal= ['Burger', 'pizza', 'steak', 'seafood boil'];
 menu.price= [15, 5, 30, 40];

 console.log(menu.todaysSpecial)
© www.soinside.com 2019 - 2024. All rights reserved.