无法从JSON数组中读取属性

时间:2014-07-22 01:49:40

标签: javascript

我正在用Javscript创建一个基于文本的游戏,我在引用JSON数组时遇到了一些问题。

var cRecipes = [];
    function craftItem(id){ 
        var n = cRecipes[id].name;
        var t = cRecipes[id].type;
        var i1 = cRecipes[id].item1;
        var a1 = parseInt(cRecipes[id].amount1);
        var i2 = cRecipes[id].item2;
        var a2 = parseInt(cRecipes[id].amount2);
        for (i = 0; i < inventory.length; i++){
            if (inventory[i].item == i1 && inventory[i].amount >= a1){
                var inv1 = parseInt(inventory[i].amount)
                parseInt(inventory[i].amount) -= a1;
                a1 = 0;
            }
            if (inventory[i].item == i2 && inventory[i].amount >= a2){
                parseInt(inventory[i].amount) -= a2;
                a2 = 0;
            }
        }
        if (a1 == 0 && a2 == 0){
            if (t == "Hat"){
                cHat = products[rId].name;
                command(products[rId].effect);
                p(n + " crafted");
            }
            else {
                p("Insufficient items");
            }
        }
    }
    function loadCrafting(){
        cRecipes = [
        {"name":"Mega Fedora", "type":"Hat", "item1": "Euphorite", "amount1":4, "item2":"Essence Of Euphoria", "amount2":2, "effect":""},
        {"name":"Mega Fedora 2", "type":"Hat", "item1": "Euphorite", "amount1":4, "item2":"Essence Of Euphoria", "amount2":2, "effect":""},
        ];   
        c();
        p("-- Your Crafting --");
        back();
        for (cr = 0; cr < cRecipes.length; cr++){
            p("<span class='choice' id='c"+ cr + "'>" + cRecipes[cr].name +", " + cRecipes[cr].type + ", " + cRecipes[cr].item1 + " x" + cRecipes[cr].amount1 + ", " + cRecipes[cr].item2 + " x" + cRecipes[cr].amount2 + "</span>");
            $("#c" + cr).click(function(){craftItem(cr);});

        }
    }

运行脚本时,我收到以下错误。

Uncaught TypeError: Cannot read property 'name' of undefined 

我在游戏的其他部分使用了类似的方法,没有任何问题,所以这个

0 个答案:

没有答案