1

JAVASCRIPT:

function identifybrand ( allproducts,favBrand){ 
  var favBrandList = new Array();
  var prodType = document.getElementById('prodType').value;
  for (var i=0;i<=allproducts.length;i++) {
    if (favBrand == allproducts[i].brandName) {
      favBrandList.push(allproducts[i]);
    }
  }
  alert(favBrandList);
}

I couldnt access the favBrandList array outside the for loop. Does anyone have any idea why i m not able to access it?

4
  • Are you getting any values in allproducts? Have you tried alerting the values? Commented Mar 26, 2013 at 10:19
  • Where do you use prodType? Commented Mar 26, 2013 at 10:24
  • yeah....if i put alert inside for loop i can see the array. but its couldn't access it outside. Commented Mar 26, 2013 at 10:35
  • I m not using it...jus kept it thr wrongly... Commented Mar 26, 2013 at 10:44

1 Answer 1

1

The reason should be you are getting a script error in the loop.

Your loop is faulty, i<=allproducts.length is wrong it should be i<allproducts.length.

Array index starts from 0 to length - 1, so when i equals allproducts.length, allproducts[i] becomes undefined and allproducts[i].brandName will throw a script error.

function identifybrand(allproducts, favBrand) {
    var favBrandList = new Array();
    var prodType = document.getElementById('prodType').value;
    for (var i = 0; i < allproducts.length; i++) {
        if (favBrand == allproducts[i].brandName) {
            favBrandList.push(allproducts[i]);
        }
    }
    alert(favBrandList);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your response. But still i m not able to access it.
what do you mean by not able to access?
i mean if i put the alert inside the for loop, i can actually see the array forming. But if i try put alert for favBrandList array out side the for loop, i m not getting any alert.
Thanks for your help. Right from the beginning i was putting i<=. :-)

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.