问题描述:

The following code returns only the "name" of the first item in the array "category". However I need it to return the "name" value of each item in the array.

What am I missing?

function loadCategories(id){

for (var i = 0; i<folder.grades.models.length; i++){

if(folder.grades.models[i].attributes.entityid==id) {

return folder.grades.models[i].attributes.categories.category[i].name;

}

}

}

网友答案:
function loadCategories(id){
   var items = folder.grades.models;
   for (var i = 0; i<items.length; i++){
      if(items[i].attributes.entityid==id) {
         return items[i].attributes.categories.category.map(function(c) {
            return c.name;
         });
      }
   }
   return [];
}
网友答案:

return exits the function, you should add all names to an array and then return that array

function loadCategories(id){
   var names = [];
   for (var i = 0; i<folder.grades.models.length; i++){
      if(folder.grades.models[i].attributes.entityid==id) {
         names[i] = folder.grades.models[i].attributes.categories.category[i].name;
      }
   }
   return names;
}
网友答案:

Return statements break out of functions, so once it hits that return statement, the function is over. If you want all of the names of the categories that match entity id:

function loadCategories(id){
   var result = [];
   for (var i = 0; i<folder.grades.models.length; i++){
      if(folder.grades.models[i].attributes.entityid==id) {
         for (var j = 0; j < folder.grades.models[i].attributes.categories.category.length; ++j) {
            result.push(folder.grades.models[i].attributes.categories.category[j].name);
         }
      }
   }
   return result;
}
相关阅读:
Top