具有键值对/For循环的优化JavaScript随机字符串

问题描述 投票:0回答:2
var crustType = ["wheat", "hand tossed", "deep dish"];
var crustTypeArr = crustType[Math.floor(Math.random() * crustType.length)];
var sauceType = ["marinara", "tomato", "none"];
var sauceTypeArr = sauceType[Math.floor(Math.random() * sauceType.length)];
var cheeses = ["mozarella", "cheddar", "feta"];
var chessesArr = cheeses[Math.floor(Math.random() * cheeses.length)];
var toppings = ["vegan sausage", "spinach", "onions", "pepperoni", "mushrooms"];
var toppingsArr = toppings[Math.floor(Math.random() * toppings.length)]

function randomPizza(crustType, sauceType,cheeses, toppings) {
    randomPizza.crustType = crustType;
    randomPizza.sauceType = sauceType;
    randomPizza.cheeses = cheeses;
    randomPizza.toppings = toppings;
    
    return randomPizza;
}

var p5 = randomPizza(crustTypeArr, sauceTypeArr, chessesArr, toppingsArr);

console.log(p5);

如果有大约一百万个变量,您将如何使用键值对/for 循环来执行此操作,或者您认为哪种方法更优化?

我得到了正确的代码,但它没有优化。

javascript function for-loop random key-value
2个回答
1
投票

您可以将选项添加到一个对象中,但不要将任何内容传递给您的函数。而是循环遍历函数中的选项并从那里随机化添加到对象。

const options = {
  crustType: ["wheat", "hand tossed", "deep dish"],
  sauceType: ["marinara", "tomato", "none"],
  cheeses: ["mozarella", "cheddar", "feta"],
  toppings: ["vegan sausage", "spinach", "onions", "pepperoni", "mushrooms"]

};

function randomPizza() {
  let pizza = {};
  
  for(key in options){
    pizza[key] = options[key][Math.floor(Math.random() * options[key].length)]
  }

  return pizza;
}

var p5 = randomPizza();

console.log(p5);


0
投票

我认为你所说的优化实际上是让它与可配置数量的成分一起工作。您可以使用以下方法这样做。

我正在使用

Object.entries()
从目录中读取和
reduce()
来构建
pizza
对象。

const crustType = ["wheat", "hand tossed", "deep dish"];
const sauceType = ["marinara", "tomato", "none"];
const cheeses = ["mozarella", "cheddar", "feta"];
const toppings = ["vegan sausage", "spinach", "onions", "pepperoni", "mushrooms"];

function randomPizza(ingredientCatalog) {
  // loop over the catalog and 
  // select one random option for each type
  return Object.entries(ingredientCatalog)
  .reduce((pizza, [ingredientType, ingredientList]) => (pizza[ingredientType] = ingredientList[Math.floor(Math.random() * ingredientList.length)], pizza), {});
}

// catalog of ingredient types and ingredients
const catalog = {
  crustType,
  sauceType,
  cheeses,
  toppings
};

// generate 5 random pizzas
console.log([...new Array(5)].map(_ => randomPizza(catalog)))
.as-console-wrapper {
    max-height: 100% !important;
    top: 0;
}

© www.soinside.com 2019 - 2024. All rights reserved.