Reputation: 57
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?
Upvotes: 1
Views: 64
Reputation: 388416
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);
}
Upvotes: 1