Javascript和Jquery: Uncaught TypeError: Cannot read property

Javascript and Jquery: Uncaught TypeError: Cannot read property 'length' of undefined

本文关键字:Cannot read property TypeError Uncaught Jquery Javascript      更新时间:2023-09-26

目前我正在写一个网站,其中一个功能是允许用户输入一张卡牌(游戏邦注:即《炉石传说》)的名称,并将其添加到网站的套牌组中。我使用JSON数据从http://hearthstonejson.com/json/AllSets.json,但是我在查询这些数据时遇到了麻烦。

现在我有:

// On user submission, searches for the inputted card name and places it into
// the deck if a match is found
$("#cardSearch").submit(function(){   
    card = $("#userInput").val();
    console.log("Card searched: " + card);
    $.getJSON("http://hearthstonejson.com/json/AllSets.json",function(cards){
       // cards = JSON.parse(cards);
        console.log(cards);
        $.each(cards.name, function(key, val){ 
            if (val.name == card) {
                console.log("Success, I found :" + val.name);
                return;
            }
        });   
    }   
    );
});

我的错误是Uncaught TypeError: Cannot read property 'length' of undefined,引用最新版本jquery的第631行

我想也许我必须解析数据,正如您在中间的注释行代码中看到的那样。但是,当我添加这一行时,我得到了一个不同的错误:

Uncaught SyntaxError: Unexpected token o.

我不知道该从哪里着手。

谢谢你的帮助-我对这个很陌生!

试试这个:

var card = $("#userInput").val();
$.getJSON("http://hearthstonejson.com/json/AllSets.json", function (cards) {
    //Returns a JSON object where cards are grouped into something like this Basic, Credits, Debug etc
    //Each of these groups contains an array of cards
    //So the first step is to loop through the groups and inside this loop through the array of cards.
    $.each(cards, function (key, val) {
        //Here val is an array of cards
        //In order to get each card we have loop through val.
        $.each(val, function (index, data) {
            //Here data is refferd to as individual card
            if (data.name == card) {
                console.log("Success, I found :" + data.name);
                return;
            }
        });
    });
});
JSON卡:

Object {Basic: Array[212], Credits: Array[17], Debug: Array[39], Expert: Array[392], Missions: Array[37]…}

我们必须使用cards.Basic[index]来获得一张特定的卡

Object {id: "GAME_004", name: "AFK", type: "Enchantment", text: "Your turns are shorter."}

这里是演示

错误表示$。不能以数组形式访问对象,这意味着它没有length属性。

你的代码应该是:

$.each(cards, function(key, val)