0

I'm new to Javascript and I have a problem to access the item inside array of array. I'm using the AngularJs framework and here is the code:

$scope.db.items4 = [];  
var newRow={
    ID:0,
    action1:[0,0,0,0,0,0,0],
    action2:[0,0,0,0,0,0,0]
    };

$scope.db.items4.push(newRow);

for (var j = 0; j < 50; j++){
   var lastRow=items4.length-1;
   var thatDay=ts.items[j].day;
   if(items4[lastRow].ID=="0"){
       items4[lastRow]=ts.items[j].ID;
       items4[lastRow].action1[thatDay]=ts.items[j].action1;
       items4[lastRow].action2[thatDay]=ts.items[j].action2;
   }else{
    if(items4[lastRow].ID==ts.items[j].ID && items4[lastRow].action2[thatDay]=="0") { 
       items4[lastRow].action1[thatDay]=ts.items[j].action1;
       items4[lastRow].action2[thatDay]=ts.items[j].action2;
        } else{
           var newRow2={
            ID:0,
            action1:[0,0,0,0,0,0,0],
            action2:[0,0,0,0,0,0,0]
            };
            $scope.db.items4.push(newRow2);
            lastRow++;
            items4[lastRow]=ts.items[j].ID;
            items4[lastRow].action1[thatDay]=ts.items[j].action1;
            items4[lastRow].action2[thatDay]=ts.items[j].action2;
            }
        }
   }

When I run it, the javascript console always says:

Uncaught ReferenceError: items4 is not defined 

But obviously items4 has been defined in the beginning; ( any help is appreciated.

4
  • 3
    If you cache items4[lastRow] you'll make that code 1000 times cleaner. Commented Apr 24, 2013 at 20:59
  • 5
    No, items4 hasn't been defined, $scope.db.items4 has been. Commented Apr 24, 2013 at 21:00
  • yeah, it looks like you have actually never defined items4...that would be something like var items4 = $scope.db.items4; Commented Apr 24, 2013 at 21:02
  • 1
    the irony is that you have typed items4 a million times and forgot to even define it. Commented Apr 24, 2013 at 21:02

1 Answer 1

1

If you wanna simplify it change the first line to be like this:

var item4 = $scope.db.items4 = [];
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks.I thought $scope.db.items4 means items4. Now there is no more "items4 is not defined " but the result is still not correct. Is items4[i].action2[j] the right way to access the element inside the array of array? thanks.
Well, you are overriding the items4[lastRow] with the ID value which i expect it to be a string or number value: >> items4[lastRow]=ts.items[j].ID; So now items4[lastRow] contains a string or number value of the ID and not the object. So calling item4[lastRow].action1 should throw an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.