2017-07-04 83 views
-1

問題與插入到一個數組

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

您需要附上在一個新函數中,第二次調用ConnectVagas,變量a總是打印爲4,因爲在javascript中,變量有一個函數作用域。爲了糾正這個問題,創建一個帶有參數current_item和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); 
    } 
    }); 
} 
+0

不錯,tnx!對 :) – concas