jquery - getting javascript error while iterating through array -
function sortproducts(filprodlist) { var prod; var k = 0; (i = 0; < filprodlist.length; i++) { var k = + 1; var p=filprodlist[i].entitykey.substr(filprodlist[i].entitykey.length - 1); var p2=filprodlist[k].entitykey.substr(filprodlist[k].entitykey.length - 1); if ( p>p2) { temp = filprodlist[k]; filprodlist[k] = filprodlist[i]; filprodlist[i] = temp; } } rederproduct(filprodlist); }
while executing above code getting following error typeerror: filprodlist[k] undefined
don't var
inside loops, blocks don't have scope in javascript, var
every variable want use in 1 var
statement. end loop when highest index reaches end (k
). can move k
for
's iterate step because you're iterating this, too.
function sortproducts(filprodlist) { var prod, i, k, p, p2, temp; (i = 0, k = 1; k < filprodlist.length; ++i, ++k) { p = filprodlist[i].entitykey.substr(filprodlist[i].entitykey.length - 1); p2 = filprodlist[k].entitykey.substr(filprodlist[k].entitykey.length - 1); if (p > p2) { temp = filprodlist[k]; filprodlist[k] = filprodlist[i]; filprodlist[i] = temp; } } rederproduct(filprodlist); }
a different way forget k
together, start i = 1
, use i - 1
, i
, means you're iterating less variables might easier follow code in mind.
Comments
Post a Comment