【问题标题】:Is it possible to store data in function to an object literal by passing argument to a function?是否可以通过将参数传递给函数来将函数中的数据存储到对象文字中?
【发布时间】:2018-09-27 14:37:21
【问题描述】:

我添加了我的 html 和 js sn-p 但是它仍然没有完成。抱歉,如果代码有点乱,这是我第一次尝试自己构建类似的东西。

`

var selectBread = document.querySelectorAll(".bread-select");
var sauceSelect = document.querySelectorAll(".sauces-select");
var checkBoxes = document.getElementsByTagName("input");
var orderModal = document.getElementById("order-modal");
let chosenItem;
let chosenItemPrice;
var ingredients = [];
var ingredientsPrice = [];
let selectedItem;
var sideDishes = [];
var drink = [];
var toasted;
var currentSandwich = {};
var breadAndPrice = [
  ["baguette", 0.8],
  ["burger bun", 0.8],
  ["ciabatta", 0.9],
  ["focaccia", 1.5],
  ["ftira", 0.8],
  ["olive bread", 1.3],
  ["rye bread", 1.3],
  ["sliced bread", 0.9],
  ["tortilla", 1.6],
  ["wheat bread", 0.9],
  ["whole grain bread", 1.2]
];
var sauceAndPrice = [
  ["chili sauce", 0.25],
  ["garlic and olive oil", 0.35],
  ["ketchup", 0.15],
  ["mayonnaisee", 0.15],
  ["garlic basil mayo", 0.45],
  ["mustard", 0.25]
];

function getBreadInfo(el, currentOption) {
  for (var i = 0; i < el.length; i++) {
    //add event listener to all bread select menu options
    el[i].addEventListener("change", function() {
      selectedItem = event.target.value; //current selected item
      getArrIndex(currentOption, selectedItem);
      if (event.target.name === "bread-select") {
        currentSandwich.breadType = chosenItem;
        currentSandwich.breadPrice = chosenItemPrice;
      } else if (event.target.name === "sauce-select") {
        currentSandwich.sauce = chosenItem;
        currentSandwich.saucePrice = chosenItemPrice;
      } else if (event.target.name === "side-dishes-select") {
        currentSandwich.sideDish = chosenItem;
        currentSandwich.sideDishPrice = chosenItemPrice;
      } else if (event.target.name === "drinks-select") {
        currentSandwich.drinkSelect = chosenItem;
        currentSandwich.drinkPrice = chosenItemPrice;
      } else if (event.target.name === "toasted-select") {
        currentSandwich.toasted = chosenItem;
      }
    });
  }
}

function getArrIndex(arr, val) {
  // val is the selected item
  for (var i = 0; i < arr.length; i++) {
    //iterate through the current choosen array
    if (arr[i][0] === val) {
      // when selected item is found in the array
      chosenItem = arr[i][0]; // store the item in choosenItem value
      chosenItemPrice = arr[i][1]; // store the item price in choosenItem value
    }
  }
}
getBreadInfo(selectBread, breadAndPrice);
getBreadInfo(sauceSelect, sauceAndPrice);
//get the index of the selected item from the bread and price array

function getIngredientsInfo() {
  for (var i = 0; i < checkBoxes.length; i++) {
    //loop check boxes
    checkBoxes[i].addEventListener("change", function() {
      //add event listener to check boxes
      if (event.target.checked) {
        //check if check boxes are checked
        ingredients.push(event.target.name); //push the name of ingredient to ingredients array
        ingredientsPrice.push(event.target.value); //get the price of the item checked from value attr and push it to ingredientsPrice array
      } else if (event.target.checked === false) {
        var index = ingredients.indexOf(event.target.name);
        ingredients.splice(index, 1);
        ingredientsPrice.splice(index, 1);
      }
    });
  }
}
getIngredientsInfo();
<section class="order-section">
  <h2 class="selection-header">Choose your...</h2>
  <div class="select-container">

    <select class="bread-select" name="bread-select">
      <option selected disabled>Bread Type</option>
      <option value="baguette">Baguette</option>
      <option value="burger bun">Burger Bun</option>
      <option value="ciabatta">Ciabatta</option>
      <option value="focaccia">Focaccia</option>
      <option value="ftira">Ftira</option>
      <option value="olive bread">Olive Bread</option>
      <option value="rye bread">Rye Bread</option>
      <option value="sliced bread">Sliced Bread</option>
      <option value="tortilla">Tortilla</option>
      <option value="wheat bread">Wheat Bread</option>
      <option value="whole grain bread">Whole Grain Bread</option>
    </select>


    <select class="sauces-select" name="sauce-select">
      <option selected disabled>Sauces</option>
      <option value="chili sauce">Chili Sauce</option>
      <option value="garlic and olive oil">Garlic and Olive Oil</option>
      <option value="ketchup">Ketchup</option>
      <option value="mayonnaise">Mayonnaise</option>
      <option value="garlic basil mayo">Garlic Basil Mayo</option>
      <option value="mustard">Mustard</option>
    </select>

    <select class="side-dishes-select" name="side-dishes-select">
      <option selected disabled>Side Dishes</option>
      <option value="coleslaw">Coleslaw</option>
      <option value="curly fries">Curly Fries</option>
      <option value="mixed salad">Mixed Salad</option>
      <option value="potato wedges">Potato Wedges</option>
      <option value="potatoes salad">Potatoes Salad</option>
      <option value="sliced Potatoes fries">Sliced Potatoes Fries</option>
      <option value="sweet potatoes fries">Sweet Potatoes Fries</option>
    </select>

    <select class="drinks-select" name="drinks-select">
      <option selected disabled>Drinks</option>
      <option value="Still Water">Still Water</option>
      <option value="Fizzy Water">Fizzy Water</option>
      <option value="coca cola">Coca Cola</option>
      <option value="sprite">Sprite</option>
      <option value="fanta">Fanta</option>
      <option value="kinnie">Kinnie</option>
      <option value="cisk">Cisk</option>
    </select>

    <select class="toasted-select" name="toasted-select">
      <option selected disabled>Toasted</option>
      <option value="yes">Yes</option>
      <option value="no">No</option>
    </select>
  </div>

</section>

`我有一个用于从选择菜单中获取数据的函数,我想通过将数据作为参数传递来将数据保存到对象中。目前我发现的唯一解决方案是使用 if 语句,但它看起来很糟糕。请问有什么帮助重构这个吗?

      if (event.target.name === "bread-select") {
    currentSandwich.breadType = chosenItem;
    currentSandwich.breadPrice = chosenItemPrice;
  } else if (event.target.name === "sauce-select") {
    currentSandwich.sauce = chosenItem;
    currentSandwich.saucePrice = chosenItemPrice;
  } else if (event.target.name === "side-dishes-select") {
    currentSandwich.sideDish = chosenItem;
    currentSandwich.sideDishPrice = chosenItemPrice;
  } else if (event.target.name === "drinks-select") {
    currentSandwich.drinkSelect = chosenItem;
    currentSandwich.drinkPrice = chosenItemPrice;
  } else if (event.target.name === "toasted-select") {
    currentSandwich.toasted = chosenItem;
  }

【问题讨论】:

  • 你能控制选择的名字吗?
  • 将其作为参数传递”是什么意思?
  • 类似这样的东西:function foo(obj){ currentSandwich.obj = chosenItem; } foo(breadType); 我知道这行不通,但为了更好地解释我自己的真正意思。
  • 这个sn-p 的代码没有包含足够的信息来说明你想要做什么。如果它是函数的一部分,您能否展示更多内容,包括参数和返回值?
  • 我认为这里没有任何重构可能。除了 switch 语句,但这并没有使它更漂亮。

标签: javascript refactoring javascript-objects


【解决方案1】:

我建议切换是要走的路,这是更快更好的做法。

switch(event.target.name) {
  case 'bread-select':
    currentSandwich.breadType = chosenItem;
    currentSandwich.breadPrice = chosenItemPrice;
    break;
  ...
  default:
}

谢谢

【讨论】:

  • 为什么你认为它更快?而且它仍然是重复的。
  • 谢谢这看起来更好但是我更喜欢它是否可以变得更干净。抱歉,我无法点赞您的消息,我的声望仍然低于 15。
  • 虽然他对每种情况都有不同的键。所以我不认为传递作为一个论点会起作用。另外,我觉得 switch case 消除了重复比较名称这样的冗余代码,甚至代码看起来也不错。
【解决方案2】:

您可以使用字符串对使用[] 括号表示法的对象进行属性分配。因此,如果您能够从您的选择中获得相关的属性名称或属性名称的一部分,那应该对您有用。

var selects = document.querySelectorAll('select');
for(var i = 0; i < selects.length; i++){
  selects[i].addEventListener('change', selectHandler);
}
var currentSandwich = {};
var prices = {
  soda : .5,
  tea : .5,
  lemonade : 1,
  water : 0,
  corn : 2,
  potatoes : 2.5,
  carrots : 1.5
};

function selectHandler(evt){
  var name = evt.target.name;
  var selection = evt.target.value;
  currentSandwich[name] = selection;
  if(prices[selection]){
    currentSandwich[name+"price"] = prices[selection];
  }else{
    currentSandwich[name+"price"] = 0;
  }
  console.log(currentSandwich);
}
<select name='drink'>
  <option value=''>Please Choose One</option>
  <option value='soda'>Soda</option>
  <option value='tea'>Tea</option>
  <option value='lemonade'>Lemonade</option>
  <option value='water'>Water</option>
</select>
<select name='side'>
  <option value=''>Please Choose One</option>
  <option value='corn'>Corn</option>
  <option value='potatoes'>Potatoes</option>
  <option value='carrots'>Carrots</option>
</select>

【讨论】:

  • 谢谢,这绝对是干净的我希望我能这么快得到解决方案。
【解决方案3】:

这是一种截然不同的方法。它在 HTML 标记中存储价格和一些键,并使用一个简单的函数来使用这些来更新您的三明治。

我不知道这种重构是否是您想要的,但这是避免这种重复逻辑的一种合理方法。

var sandwich = {};
var sandwichContainer = document.getElementById('sandwich-options');
sandwichContainer.addEventListener('change', function(ev) {
  var select = event.target;
  var choice = select.selectedOptions[0];
  var choiceName = select.dataset.choiceName;
  sandwich[choiceName] = choice.value
  var priceName = select.dataset.choicePrice;
  if (priceName) {
    sandwich[priceName] = Number(choice.dataset.price);
  }
  console.log(sandwich)
});
<section class="order-section">
  <h2 class="selection-header">Choose your...</h2>
  <div id="sandwich-options">

    <select class="bread-select" name="bread-select" 
            data-choice-name="breadType" data-choice-price="breadPrice">
      <option selected disabled>Bread Type</option>
      <option value="baguette" data-price="0.8">Baguette</option>
      <option value="burger bun" data-price="0.8">Burger Bun</option>
      <option value="ciabatta" data-price="0.9">Ciabatta</option>
      <option value="focaccia" data-price="1.5">Focaccia</option>
      <option value="ftira" data-price="0.8">Ftira</option>
      <option value="olive bread" data-price="1.3">Olive Bread</option>
      <option value="rye bread" data-price="1.3">Rye Bread</option>
      <option value="sliced bread" data-price="0.9">Sliced Bread</option>
      <option value="tortilla" data-price="1.6">Tortilla</option>
      <option value="wheat bread" data-price="0.9">Wheat Bread</option>
      <option value="whole grain bread" data-price="1.2">Whole Grain Bread</option>
    </select>


    <select class="sauces-select" name="sauce-select" data-
            choice-name="sauce", data-choice-price="saucePrice">
      <option selected disabled>Sauces</option>
      <option value="chili sauce" data-price="0.25">Chili Sauce</option>
      <option value="garlic and olive oil" data-price="0.35">Garlic and Olive Oil</option>
      <option value="ketchup" data-price="0.15">Ketchup</option>
      <option value="mayonnaise" data-price="0.15">Mayonnaise</option>
      <option value="garlic basil mayo" data-price="0.45"
          >Garlic Basil Mayo</option>
      <option value="mustard" data-price="0.25">Mustard</option>
    </select>

    <select class="toasted-select" name="toasted-select" data-choice-name="toasted">
      <option selected disabled>Toasted</option>
      <option value="yes" data-price="0">Yes</option>
      <option value="no" data-price="0">No</option>
    </select>
  </div>

</section>

另一种方法是将所有价格存储在由选择名称键入的对象中,如下所示:

var prices = {
  'bread-select': {
    'baguette': 0.8, 
    ...
   }, 
   'sauces-select': {
     'chili sauce': 0.25, 
     ...
    }, 
    ...
};

然后使用上面的select.namechoice.value 键入这个对象。您还需要另一个对象,或者一种增强该对象以存储最终属性名称的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 2021-03-29
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多