Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
Reinicie la aleatorización después de que pase por todos los elementos de la matriz

Estoy aprendiendo JS y acabo de terminar un proyecto, aquí el código:

 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!!"); }

Al final del código, agregué un par de matrices y un Math.random para que cada vez que lo ejecute, me dé un valor diferente.

Ahora estoy tratando de encontrar una manera de que el valor aleatorio proporcione valores únicos hasta que alcance la longitud de la matriz y luego reinicie. En este momento tengo 7 elementos en la matriz que simulan el día de la semana, me gustaría que cada elemento salga una vez por semana y luego se reinicie.

Sé cómo hacerlo siguiendo el orden del índice de matriz, pero no puedo encontrar una forma de hacerlo al azar, ¿alguna entrada?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Puede combinar su matriz de precios y comidas para hacerlo un poco más simple y luego mezclarlo.

 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); }
about 4 years ago · Juan Pablo Isaza Relatório

0

Es fácil cada vez que selecciona un valor de la matriz, elimínelo y cuando la matriz finalice, simplemente restablezca la matriz al valor inicial. Para no tener problemas con el número aleatorio, debería ser así Rand=Math.random()*array.lenght ;

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda