我刚开始学习Javascript,无法弄清楚为什么我的代码与我看到的其他代码表现得如此不同。我创建了一个简单的网页,该网页基本上只有一个div,其ID为“ sheet3-3”,并在JS中进行了更新。像这样:
var num_arr = [["1", 2], ["3", 4]];
req = new XMLHttpRequest();
req.open("GET",'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json',true);
req.send();
req.onload=function() {
obj = JSON.parse(req.responseText);
obj = obj.data;
obj.forEach(function(val) {
num_arr.push(val);
});
document.getElementById('sheet3-3').innerHTML = num_arr;
};
结果,网页看起来像这样:
1,2,3,4,1947-01-01,243.1,1947-04-01,246.3,....
这是预料之中的,因为初始num_arr是全局变量,并由json数据数组附加。
但是,如果我将部分document.getElementById('sheet3-3').innerHTML = num_arr;
移动到示波器之外,就像这样:
var num_arr = [["1", 2], ["3", 4]];
req = new XMLHttpRequest();
req.open("GET",'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json',true);
req.send();
req.onload=function() {
obj = JSON.parse(req.responseText);
obj = obj.data;
obj.forEach(function(val) {
num_arr.push(val);
});
};
document.getElementById('sheet3-3').innerHTML = num_arr;
该网页现在仅显示1,2,3,4
。
为什么全局变量不再更新了?
如果您想看一下html,还附有该代码段。
var num_arr = [["1", 2], ["3", 4]];
req = new XMLHttpRequest();
req.open("GET",'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json',true);
req.send();
req.onload=function() {
obj = JSON.parse(req.responseText);
obj = obj.data;
obj.forEach(function(val) {
num_arr.push(val);
});
};
document.getElementById('sheet3-3').innerHTML = num_arr;
<!DOCTYPE HTML>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
<title>Working Code Camp</title>
<link rel="stylesheet" type="text/css" href="code_camp_css_test.css">
</head>
<body>
<center>
<header>
<h1>Demo</h1>
</header>
<main>
<h3>JSON Parsing</h3>
<section id = 'sheet3-3'>
</section>
</main>
<footer>
</footer>
</center>
<script type="text/javascript" src="http://d3js.org/d3.v5.min.js" charset="utf-8"></script>
<script type="text/javascript" src="code_camp_js_test.js"></script>
</body>
</html>