简体   繁体   中英

Issue in iterating the array in javascript

I have an array named a[] which contains the city_id and city name

Then I am doing edit and i get the details such as cityID , countryid ,etc

and save it in var b= cityID

Now to get the cityname and appending to the field textbox

i am iterating the array a thru each function

 function f1() {
     jQuery(a). each(function(m) {
         if(this.city_id(from array a) == cityID)
             if(c== "") {
                 c += this.cityname;
             } else {
                 c += ","+ this.cityname;
             }
     }); 
 }

c is a global var the problem is on click of edit i get c as say Bombay , Delhi , Puna

but again next time if i click on another radio button to fetch that details it gets appended to Bombay , Delhi , Puna , Chennai like this instead of clearing the first one.

You need to reset c to an empty string at the beginning of the function:

function f1() {
    c = '';
    $(a).each(...);
}

Instead of using global variable c you can make c a local variable and return it at end of your function .

function f1() {
  var c ='';
  jQuery(a). each(function(m) {
     if(this.city_id(from array a) == cityID)
         if(c== "") {
             c += this.cityname;
         } else {
             c += ","+ this.cityname;
         }
  }); 
  return c;
}

try this.. Here i each obj in an array.

$.each( a, function( i, val ) {
  if(i.city_id== cityID)
             if(c== "") {
                 c += this.cityname;
             } else {
                 c += ","+ this.cityname;
             }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM