Facundo Laxalde Facundo Laxalde - 27 days ago 16
Javascript Question

How can I add items to an array in JavaScript?

I'm having a simple problem, I have this code :

$http(req).then(function success(response) {
// $scope.table = { fields: [1,2] };
$scope.table = { fields: [] };
for (var i = 0; i < 9; i++) {
// add elements from response to $scope.table
}
});


The question is: how do I add elements to my variable
$scope.table
?

As we know, variables in JavaScript are not strongly-typed. I can't find any documentation that explains how to manage a type generated by something like this
{ ID: [] }
.

Answer

Actually, the variable $scope.table is an Object which has an array property (at key) fields. With that array, use array.prototype.push() to add elements to the end of the array.

e.g.

$http(req).then(function success(response) {
// $scope.table = { fields: [1,2] };
$scope.table = { fields: [] };
for (var i = 0; i < 9; i++) {
    // add elements from response to $scope.table
    $scope.table.fields.push(response[i]);
 }
Comments