在javascript中迭代数组时出现问题

Issue in iterating the array in javascript

本文关键字:问题 数组 javascript 迭代      更新时间:2023-09-26

我有一个名为a[]的数组,其中包含city_id和城市名称

然后我进行编辑,我得到了cityIDcountryid等的详细信息

并保存在var b= cityID

现在获取cityname并将其附加到字段textbox

我正在通过每个函数迭代数组

 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是全局var,问题是点击编辑我得到c,比如BombayDelhiPuna

但下次如果我点击另一个单选按钮获取详细信息,它会像这样附加到BombayDelhiPunaChennai,而不是清除第一个。

试试这个。。这里我把每个obj都放在一个数组中。

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

您可以将c设为局部变量,并在function结束时返回它,而不是使用全局变量c

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;
}

您需要在函数开头将c重置为空字符串:

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