javascript - 代表同一产品 3 个不同价格的价格数组

标签 javascript jquery arrays json

我正在尝试创建一个数组,代表三个不同的商家,这些商家对相同产品持有不同的价格(稍后在代码中表示哪些商家)。 我的逻辑似乎不正确,我希望通过一个例子来帮助我了解如何正确地完成这一任务。 附件是我的代码,但请仅注意 Merchantprices 和 getRecipeItems 部分。

JS

var main = function () {

    var recipeType = {
        0: {"name": "cocktail", "ingredients": ["Booz","Roofis","Green Stuff"]},
        1: {"name": "appetizer", "ingredients": ["Some leaves","Some veggies", "I dunno toast","Cheese or whatever"]},
        2: {"name": "main course", "ingredients": ["A dead animal","its blood", "some potatoes","love","asparagus"]} ,
        3: {"name": "dessert", "ingredients": ["Dough","Some Sprinkly shit", "sugar","more sugar","cream shaboogy pop"]} ,
    }

    var Merchantprices = {

        ampm:{"ingredientPrice":recipeType[0].ingredients = 20,"sumPrice":recipeType[0] = ingredientPrice * (recipeType[0].ingredients.length)},
        haCarmel:{},
        tivTaam:{},

    }

    function getRecipeItems() {
        return recipeItems = [
            {
                "id": "recipe0",
                "title": "Grasshopper Cocktail",
                "img": "../images/grasshopper-cocktail.jpg",
                "ingredients": recipeType[0].ingredients,
                "instructions":"shaken not stirred",
                "price": {"ampmPrice":Merchantprices[0].sumPrice,"haCarmelPrice":Merchantprices[1].sumPrice,"tivTaamPrice":Merchantprices[2].sumPrice},
                "type" : recipeType[0].name,
            },
            {
                "id": "recipe1",
                "title": "Beef roast with veggies",
                "img": "../images/beef-roast-with-veggies.JPG",
                "ingredients": recipeType[2].ingredients,
                "instructions":"stuff it good",
                "price": 55,
                "type" : recipeType[2].name,
            },
            {
                "id": "recipe2",
                "title": "Shrimp-Fried-Rice",
                "img": "../images/Shrimp-Fried-Rice.jpg",
                "ingredients": recipeType[1].ingredients,
                "instructions":"extra MSG",
                "price": 65,
                "type" : recipeType[1].name,
            },
            {
                "id": "recipe3",
                "title": "Cupcake from hell",
                "img": "../images/Cupcake-Idea-pics-200x150.png",
                "ingredients": recipeType[3].ingredients,
                "instructions":"death is inevitable",
                "price": 15,
                "type" : recipeType[3].name,
            },
        ]
    }

    function createRecipeItem(recipeItem) {
        var recipeElement = document.createElement('div');
        recipeElement.setAttribute("id", recipeItem.id);
        recipeElement.setAttribute("class", recipeItem);

        recipeDetailsElement = document.createElement("div");
        recipeDetailsElement.setAttribute("id", recipeItem.id+"_details");

        recipeDetailsElement.appendChild(createDeleteRecipe(recipeItem));
        recipeDetailsElement.appendChild(createRecipePic(recipeItem));
        recipeDetailsElement.appendChild(createRecipeTitle(recipeItem));

        recipePreperationElement = document.createElement("div");
        recipePreperationElement.setAttribute("id", recipeItem.id+"_full_details");
        recipePreperationElement.appendChild(createRecipeIngredients(recipeItem));
        recipePreperationElement.appendChild(createRecipeInstructions(recipeItem));
        recipePreperationElement.style.display = 'none';

        recipeDetailsElement.appendChild(recipePreperationElement);


        recipeElement.appendChild(createUndoDeleteRecipe(recipeItem));
        recipeElement.appendChild(recipeDetailsElement);


        return recipeElement;

    }
    function createUndoDeleteRecipe(recipeItem) {
        var undoButton = document.createElement('span');
        undoButton.setAttribute("id", recipeItem.id + "_undo");
        undoButton.setAttribute("class", "fa fa-undo", "aria-hidden", "true");
        $(undoButton).hide();
        $(undoButton).click(() => {
            onItemDeleteUndo(recipeItem);
        });
        return undoButton;
    }
    function createDeleteRecipe(recipeItem) {
        var deleteButton = document.createElement('span');
        deleteButton.setAttribute("class", "fa fa-times-circle", "aria-hidden", "true");

        $(deleteButton).click(() => {
            onItemDelete(recipeItem);
        });

        return deleteButton;
    }

    function onItemDelete(recipeItem) {
        $('#'+recipeItem.id+'_details').hide();
        $('#'+recipeItem.id+'_undo').show();
    }

    function onItemDeleteUndo(recipeItem) {
        $('#'+recipeItem.id+'_details').show();
        $('#'+recipeItem.id+'_undo').hide();
    }

    function createRecipeTitle(recipeItem) {
        var div = document.createElement('div');
        div.innerHTML = recipeItem.title;
        return div;
    }

    function createRecipeInstructions(recipeItem) {
        var div = document.createElement('div');
        div.innerHTML = recipeItem.instructions;
        return div;
    }

    function createRecipePic(recipeItem) {
        var recipePic = document.createElement("img");
        recipePic.setAttribute("src", recipeItem.img);
        recipePic.setAttribute("class", "recipe");
        $(recipePic).css('margin-top', '10px');

        $(recipePic).click(() => {
            $('#'+recipeItem.id+"_full_details").slideToggle();
        });

        return recipePic;
    }

    function createRecipeIngredients(recipeItem) {
        var ingredients = document.createElement("ul");
        ingredients.setAttribute("id", recipeItem.id + "_ingredients");
        ingredients.className = "ingredientsList";

        recipeItem.ingredients.forEach(ingredient => {
            var li = document.createElement("li");
            li.className = "ingredients";
            li.setAttribute("type", "checkbox");

            var checkbox = document.createElement("input");
            checkbox.setAttribute("type", "checkbox");
            li.appendChild(checkbox);

            var ingredientElement = document.createElement("a");
            ingredientElement.innerHTML = ingredient;
            li.appendChild(ingredientElement);

            ingredients.appendChild(li);
        })
        return ingredients;

    }

    recipeItems = getRecipeItems();
    var mainContainer = document.getElementsByClassName('mainContainer');
    recipeItems.forEach(recipeItem => {
        mainContainer[0].appendChild(createRecipeItem(recipeItem));
    });



};
var recipeItems;
var Merchantprices;
$(document).ready(main);

最佳答案

好的,所以我想我得到了你想要做的事情。这里有两个解决方案:

将所有内容保存在一处

function getRecipeItems() {
    return recipeItems = [
        {
            "id": "recipe0",
            // ...
            "price": {
                default: 8,
                ampm: 10,
                // -- haCarmel: 12, -- Let's omit this one
                tivTaam: 15,
                get: function( merchant ) {
                    return this[merchant] ? this[merchant] : default;
                }
            }
        },
        // ...
    ]
}

// ---------------------------------------
// Usage
// ---------------------------------------

// Result : 8 (default price, as you didn't specify the merchant).
getRecipeItems()[0].price.get();

// Result : 10.
getRecipeItems()[0].price.get("ampm"); 

// Result : 8 (default, as you didn't set this value).
getRecipeItems()[0].price.get("haCarmel"); 
<小时/>

商人的魔法计算

您还可以设置默认价格,但将其发送给商家并进行更改。

// Price 
"price": {
    default: 8,
    get: function( merchant ) {
        return Merchants[ merchant ] 
            ? Merchants[ merchant ].getPrice( this.default ) 
            : this.default;
    }
}

// Merchants
Merchants {
    ampm: {
       //...
       getPrice: function( price ){
           return price + itemRarity - discount + etc;
       }
    },
    // ...
};
<小时/>

在这两种情况下,...

您应该为MerchantRecipeItemRecipeItemPrice创建一个对象。您的代码将更加干净,而且每次创建价格时您都不会创建 get() 函数的实例。好吧,您应该对所有游戏对象执行此操作。 :)

// Price 
var RecipeItemPrice = function( value, ... ) {
    this.default = value;
};

RecipeItemPrice.prototype.get = function() {
    // For example, if you take the second choice : 
    return Merchants[ merchant ] 
        ? Merchants[ merchant ].getPrice( this.default ) 
        : this.default;
};

关于javascript - 代表同一产品 3 个不同价格的价格数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46023809/

相关文章:

javascript - 悬停时激活 Popover 并单击任意位置关闭

javascript - 如何以 Angular 2制作 "loading"屏幕

javascript - 添加 preventDefault() 和 stopPropagation()

javascript - 如何在使用 Javascript 在 Chrome 中加载图像时对它们进行计数?

javascript - 这个 JS 函数会被视为递归吗?

c++ - 确定一个数组是否可以分成两个子序列,每个子序列的顺序都是递增的

javascript - 如何使用字段填充用户对象

javascript - Tornado 网络服务器和 Ember.js

jQuery 循环遍历表单元素并选择特定的 id

javascript - 按 id 筛选数组 angularjs 的数组