使用Mike Bostok多系列折线图示例遇变量未定义错误求助
cities/data is undefined in the console, plus the structure of cities Hey there! Let's break down your problem and answer your questions clearly:
1. Why you're getting the ReferenceError
The cities and data variables in Mike Bostock's example are local to the callback function that handles the TSV data loading. If you peek at the original code, it’s structured something like this:
d3.tsv("data.tsv", function(error, data) { // `data` only exists inside this function scope var cities = data.map(function(d) { // Transform raw TSV data into usable city objects return { // ... transformed properties here }; }); // Rest of the visualization code uses `cities` here });
Since these variables aren’t attached to the global window object, typing console.log(cities) directly in the browser console (which runs in the global scope) means the browser can’t find them—hence the ReferenceError.
Quick ways to inspect the variables:
- Use a breakpoint: Open your browser’s DevTools, go to the Sources tab, find the line where
citiesis defined, and set a breakpoint. When the code pauses there, you can typecitiesordatain the console to view their values. - Expose to global scope: Temporarily add
window.cities = cities;right aftercitiesis created in the callback. Once the data loads, you’ll be able to logcitiesin the console anytime.
2. Structure of the cities data
In this bubble map example, cities is an array of objects created by transforming the raw data from the data.tsv file. Each object includes:
- Raw properties from the TSV:
name(city name),population(numeric population value),lat(latitude),lon(longitude). - Computed visualization properties:
x: Longitude converted to an x-coordinate on the SVG canvas.y: Latitude converted to a y-coordinate on the SVG canvas.r: A bubble radius calculated from the city’s population (to size bubbles proportionally).
Here’s a simplified example of a single cities object:
{ name: "New York", population: 8405837, lat: 40.7127, lon: -74.0059, x: 350, // Example canvas x-position y: 220, // Example canvas y-position r: 45 // Example bubble radius based on population }
The raw data.tsv file uses tab-separated values, with each row representing a city and columns for the properties listed above.
内容的提问来源于stack exchange,提问作者Brian

