Reputation: 1211
I am new to html and I am trying to set my variable data
as an array of objects containing the rows of a csv file. When I run my code and inspect the page, the console says "Cannot read property 'length' of undefined." However, when I then type data.length
in the console, it prints 18411 (the number of rows in my csv file). How come I still get this error when I can clearly print out the length in the console?
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type = "text/javascript">
var data;
d3.csv("../Data/crime_2016.csv", function(d){
data = d;
});
var length = data.length;
</script>
</head>
<body>
</body>
</html>
Upvotes: 1
Views: 1168
Reputation: 1951
This has to do with variable scope and callbacks.
You are assigning data = d
in the callback of the d3.csv function. Because you are defining data outside of the function data is available to view in the console after the function has ran.
However, in your code you are trying to access the length property of data before the callback has executed at which time data
has been declared but no value assigned to it hence length is a property of an undefined
variable.
If you want to access the data.length
in your code you will need to do it inside the callback function or otherwise return a promise from your callback.
var data;
d3.csv("../Data/crime_2016.csv", function(d){
data = d;
var length = data.length;
});
Upvotes: 4