Mikky
Mikky

Reputation: 13

AngularJs: Getting unexpected output while assigin value in array?

I am trying this to get 2 values to be inserted in an js array.

$scope.ttabs = [];

for(p = 1; p <= $scope.no_of_groups; p++) {
    $scope.ttabs[p] = [1];  
    console.log($scope.ttabs);  
}

the p $scope.no_of_groups is here has value 2.

Now I am getting console output as ..

[undefined, [1], [1]]

why does it showing undefined at first index?

Upvotes: 0

Views: 57

Answers (3)

Suren Srapyan
Suren Srapyan

Reputation: 68685

Because you start from the index 1. Array's index starts from the 0. In your code you don't assign any value to the index 0, so it will have the default value which is undefined.

Change you code into to start from the 0, and also remove the equal sign from the condition.

$scope.ttabs = [];

for(var p = 0; p < $scope.no_of_groups; p++) {
    $scope.ttabs[p] = [1];  
    console.log($scope.ttabs);  
}

console.log($scope.ttabs);  

Output

[[1], [1]]

Upvotes: 3

Espen
Espen

Reputation: 2576

Because you start p = 1, when you assign that as an index to the array, the array is allocated with length 2, since arrays are index from index 0. Since nothing is inserted into the array at index 0, that index is undefined.

var ar = [];
for(var i = 1;i < 2;i++){
   ar[1] = 1;
}
console.log(ar) // outputs [undefined, 1, 1]

while:

var ar = [];
for(var i = 0;i < 2;i++){
   ar[1] = 1;
}
console.log(ar) // outputs [1, 1]

Upvotes: 0

pareshm
pareshm

Reputation: 4984

    $scope.ttabs = [];

    for(p = 0; p <= $scope.no_of_groups; p++) {
        $scope.ttabs[p] = [1];  
        console.log($scope.ttabs);  
    }

Javascript array starts from 0th index so you are getting undefined for 1st place

Upvotes: 2

Related Questions