访问范围之外的变量?

时间:2017-10-17 22:13:52

标签: javascript scope global-variables

我知道之前已经提出过这个问题;但是,我仍然遇到这个概念的问题。正如您所看到的,第一个函数在将“profile”设置为全局变量时起作用,但是当我尝试使用第二个函数模仿相同的结果时,我遇到了麻烦。我收到resultArray is not defined错误。

function profileloader() {
  profile = []; // no "var" makes this global in scope
  profile[0] = "Joe";
  profile[1] = "Bloggs";
  profile[2] = "images/joeb/pic.jpg";
  profile[3] = "Web Site Manager";
}
profileloader(); // mandatory
document.write("Firstname is: " + profile[0]);

function pressme() {
  $.getJSON('//freegeoip.net/json/?callback=?', function(data) {
    console.log(JSON.stringify(data, null, 2));

    //Testing to see if response returns correctly
    var response = (data);
    console.log(response);
    resultArray = [];
    resultArray[0] = response.country_name;
    console.log(resultArray[0]);
    document.getElementById("demo").innerHTML = response.country_name;
  });
}

pressme();
document.write("Country is: " + resultArray[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h3> Returns Country of Origin from users IP Address</h3>
<p id="demo"></p>

0 个答案:

没有答案