I'm sorry if this is a duplicate, but I've read a few posts about variable scope and I can't seem to figure this out. Any help is much appreciated.
Basically, I'm just trying to read in a csv and determine how many rows it has and then assign number to a global variable. Here is my code:
<script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script>
<script type="application/javascript">
var maxEpochs;
setMaxEpochs();
console.log(maxEpochs);
function setMaxEpochs() {
/*
for (i = 0; i < 2; i++) {
if ( document.chooseModel.model[i].checked ) {
modelChoice = document.chooseModel.model[i].value;
break;
}
}
console.log(modelChoice);
*/
// set initial value for maxEpochs I DON'T UNDERSTAND WHY THIS DOESN'T WORK
d3.csv("epochStats.csv", function(d) {
console.log(d.length);
maxEpochs = d.length;
console.log(maxEpochs);
});
console.log(maxEpochs);
}
</script>
NOTE: epochStats.csv
just has to be a csv with a few lines in it. That data doesn't matter for this example.
So, when I run this I get the following output in my console:
maxEpochsFail.html:31 undefined
maxEpochsFail.html:12 undefined
maxEpochsFail.html:27 101
maxEpochsFail.html:29 101
The line numbers might not quite match (I have some <head>
tags etc at the top), but the point is, the first two console.logs within the function print 100
which is the correct number, but then once I'm outside the function it reverts to undefined
.
Any thoughts on this would be much appreciated. I'm kind of banging my head against the wall with it. Thanks, Seth