我遇到了一个有趣的问题,让我感到困惑。我正在调用Sharepoint RestAPI,返回数据正确,但当我在数据上运行for循环时,它会构建出HTML,但仍会抛出我用作标题的错误。以下是代码。如果我在每次循环时都记录控制台日志,它将返回该值。HTML 也可以正常工作。问题在于错误仍然出现。
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);
}
}
i<=slideData.length
应该改为i < slideData.length
。这是一个经典的 off-by-one 错误。熟悉如何访问和处理嵌套对象、数组或 JSON,使用Array
的可用静态和实例方法。 - Sebastian Simon