Javascript / jQuery使循环外的变量可访问

时间:2016-05-19 11:40:40

标签: javascript jquery loops variables scope

我有一个循环,我用来改变看起来像这样的字符串

  for (var key in streets) {
    var re = new RegExp(key, 'gi');
    var address2_2 = address2.replace(re, streets[key]).replace(/\s/g, '');
  }

如果我在循环中使用变量'address2_2'就可以了,循环可以很好地完成它的工作。问题是我需要能够在循环外部访问它。我已经尝试了各种我能想到的组合来检索它,就像下面的代码片段一样。

  var address2_2 = '';
  for (var key in streets) {
    var re = new RegExp(key, 'gi');
    address2_2 = address2.replace(re, streets[key]).replace(/\s/g, '');
  }

  var address2_2 = '';
  for (var key in streets) {
    var re = new RegExp(key, 'gi');
    address2_2 = address2.replace(re, streets[key]).replace(/\s/g, '');
    return address2_2;
  }

  for (var key in streets) {
    var re = new RegExp(key, 'gi');
    window.address2_2 = address2.replace(re, streets[key]).replace(/\s/g, '');
  }

有更多的组合,但我不记得它们。我只需要能够在此循环之外的if语句中使用'address2_2'。任何帮助一如既往地受到赞赏。感谢

编辑:这是terrible jsfiddle我快速为那些问过的人做了

完整的代码是这样的

var streets = {
  "AVE": "AVENUE",
  "BLDG": "BUILDING",
  "BLVD": "BOULEVARD",
  "CIR": "CIRCLE",
  "CLL": "CALLE",
  "CR": "COUNTY ROAD",
  "CTR": "CENTER",
  "CTY": "CITY",
  "DR": "DRIVE",
  "EXT": "EXTENSION",
  "FM": "FARM ROAD",
  "HC": "HIGHWAY CONTRACT",
  "HWY": "HIGHWAY",
  "LN": "LANE",
  "MT": "MOUNT",
  "PL": "PLACE",
  "PLZ": "PLAZA",
  "PKWY": "PARKWAY",
  "PT": "POINT",
  "RD": "ROAD",
  "RT": "ROUTE",
  "RTE": "ROUTE",
  "SQ": "SQUARE",
  "SR": "STATE ROUTE",
  "ST": "STREET",
  "STE": "SUITE",
  "TR": "TRAIL",
  "WY": "WAY",
};

var address2 = '850 BULL ST';

  for (var key in streets) {
    re = new RegExp(key, 'gi');
    address2_2 = address2.replace(re, streets[key]).replace(/\s/g, '');
    console.log(address2_2);
  }
  console.log(address2_2);

1 个答案:

答案 0 :(得分:2)

在javaScript中,只有function范围,意思是,在循环内声明变量,自动将变量声明放在循环外。

var address2_2, // undefined
    re; // undefined

for (var key in streets) {
    re = new RegExp(key, 'gi');
    address2_2 = address2.replace(re, streets[key]).replace(/\s/g, '');
}

// then use it in an if else claus
if (address2_2){
    // do something
}

修改

哦,对,var key同样如此。万一你想知道。因此,如果找不到任何功能,它们将被绑定到最近的函数或窗口对象。

编辑2:

要提供解决方案,也许可以分叉fiddle

最好是在空格上拆分地址,然后与数组进行比较。 多次出现时问题的简短解决方案...

var streets = {/**/},
    input = '850 BULL ST PLZ',
    address = input.split(' '),
    arr = [],
    i = 0,
    chunk;

for (; i < address.length; i++) {
    chunk = streets[address[i]] || address[i]; // undefined or original
    arr.push(chunk);
}

$("#loop").append(address.join('<br />'));
$("#result").append(arr.join(' '));