4

I am running into an interesting issue that is throwing me for a loop. I am doing a Sharepoint RestAPI call that returns data correctly, when I run a for loop over the data it builds out the html but still tosses the error that I used as the title. Code is below. If I console log each loop it will return the value. The HTML also works fine. The issue is that error still comes up.

function getSlideData() {
    var query = "$expand=AttachmentFiles&$select=Title,Team,State,Location,Hobbies,Favorite,Askme,GreatPlace,imageFact,ImageText,Attachments,AttachmentFiles&$expand=AttachmentFiles&$top=1000&$orderby=Created desc&$filter=Display eq 'Active'";
    var svcUrl = SITE_URL + "_api/web/lists/getbytitle('"+LIST_NAME+"')/items?"+query;
    var employeeData;

    $.ajax({
        url: svcUrl,
        type: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        async: false,
        success: function (data) {
            employeeData = data.d.results;
        },
        error: function (xhr) {
            alert("Can't get list items.", xhr.status + ": " + xhr.statusText); 
        }
    });

    return employeeData;
}

function buildSlides() {
    var slideData = getSlideData();
    var sliderWrapper = $('#slider-wrapper');
    var sliderWrapperContent = "";

    for(i=0;i<=slideData.length;i++) {
        sliderWrapperContent += '<div><h2>'+slideData[i].Hobbies+'</h2></div>';
        sliderWrapper.html(sliderWrapperContent);
    }
}
OMGDrAcula
  • 1,054
  • 3
  • 11
  • 17
  • 2
    `i<=slideData.length` should be `i < slideData.length`. This is a classic off-by-one error. Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and use the available static and instance methods of [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods) instead. – Sebastian Simon Sep 08 '21 at 15:17

1 Answers1

5

The error is that you are trying to access an index that does not exist in the array because of <= in the for loop, try to use < when you use .length of an array.

Jake
  • 9
  • 3