You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Mike Bostok多系列折线图示例遇变量未定义错误求助

Why 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 cities is defined, and set a breakpoint. When the code pauses there, you can type cities or data in the console to view their values.
  • Expose to global scope: Temporarily add window.cities = cities; right after cities is created in the callback. Once the data loads, you’ll be able to log cities in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:59:16