插入数组的问题

时间:2017-07-04 03:09:27

标签: javascript angularjs

vm.categorias = function () {
  ConectaVagas('get', 'categorias').then(function (val) {
      vm.categorias = val;
      for (var a = 0; a < vm.categorias.length; a++) {
          console.log(a); // Here returns 0,1,2,3 ( number with categories )
          ConectaVagas('get', 'subcategoria', vm.categorias[a].id_categoria).then(function (val) { // List the subcategories related the categorie in loopfor
              vm.subAplicar = val;
              console.log(a); // Here returns the number 4 but i want returns 0, 1, 2, 3 and i do the insertion in arrayNova
              vm.categoria[a].arrayNova = vm.subAplicar;
          });
      }
  });
}

我需要在对象vm.category [a]中插入一个包含所有子类别的数组(arrayNova),但我不遵循:(

1 个答案:

答案 0 :(得分:1)

您需要在新函数中包含对ConnectVagas的第二次调用。您的变量a始终打印到4,因为在javascript变量中有一个函数范围。为了纠正这个问题,使用参数current_item和a创建一个匿名函数,因此a的值不会被覆盖,因为它会创建一个新的函数范围。

vm.categorias = function() {
  ConectaVagas('get', 'categorias').then(function(val) {
    vm.categorias = val;
    for (var a = 0; a < vm.categorias.length; a++) {
      console.log(a); // Here returns 0,1,2,3 ( number with categories )
      var categorias_item = vm.categorias[a].id_categoria
      (function(categorias_item, a) {
        ConectaVagas('get', 'subcategoria', categorias_item.id_categoria).then(function(val) { // List the subcategories related the categorie in loopfor
          vm.subAplicar = val;
          console.log(a); // Here returns the number 4 but i want returns 0, 1, 2, 3 and i do the insertion in arrayNova
          categorias_item.arrayNova = vm.subAplicar;
        });
      })(categorias_item, a);
    }
  });
}