简体   繁体   中英

getJSON getting all items but has undefined error

I'm using getJSON for my JSON data items, like this:

$.getJSON(projects, function (json) {
        var firstThree = json.sort(function(a, b) { return a.Variable1 < b.Variable1 ? 1 : -1; })
        .slice(0, 3);
        var related = firstThree;
        var i = '';
        $.each(json, function(i) {
            var sizeClass = JSON.stringify(related[i].pname);
            console.log('sifzdfze'+sizeClass);
        });

I checked on console, getting sizeClass item, it works. But but it also shows an error:

 related[i] is undefined

What's the problem? Thanks!

As per your code you are accessing related as an array. So you are supposed to iterate over the items in the array. In your case related[i] is undefined because you are trying to access an item that is out of bounds of the particular array.

$.each(json, function(i) {

supposed to be

$.each(related, function(val, i) {

Also the above line, creates an i that is scoped to the each callback. So there is not need to declare it in the line above. Here val is the current value in iteration whose index is i . It can be simplified as

$.each(related, function(val, i) {
   var sizeClass = JSON.stringify(val.pname);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM