如何在 D3.js 中显示对象数组

How do display array of Objects in D3.js

所以我有一个 .csv 文件 final_news_events.csv 我想在网站上显示的内容。

文件 new_event_list.html 第 151 行的以下 D3.js 代码没有按照我想要的方式工作:

<script type="text/javascript">
  d3.select("body").append("p").text("New paragraph!");
  var final_news_events = [];
  d3.csv("final_news_events.csv")
                            .row(function(d) { return {news_event: d.News_Event}; })
                            .get(function(error, rows) { 
                              console.log(rows); 
                              final_news_events = rows;
                            });
  d3.select("body").append("ol").selectAll("text")
    .data(final_news_events)
    .enter()
    .append("li")
    .text(function(d) {
      return "Object 2";
  });
</script>  

我已将我的代码推送到 github & heroku,因此实时 heroku 网站位于 https://neweventdetection.herokuapp.com/

如果您打开此网站上的控制台并转到 Google chrome 中的 "Elements",您可以看到某些 D3.js 代码正在运行:

<p>New paragraph!</p>
<ol></ol>

但是如何让它显示:

<p>New paragraph!</p>
<ol>
  <li>White House moves to take Cuba off Terrorism List</li>
  <li>US plans stiffer rules protecting retiree cash</li>
  <li>Rival Factions in Ukraine Are Urged to Withdraw Heavy Weapons</li>
  <li>Boko Haram Abducted Nigerian Girls One Year Ago</li>
</ol>

就像弗兰克在他的回答的后半部分解释的那样:

数据加载是异步的,所以这段代码:

d3.select("body").append("ol").selectAll("text")
  .data(final_news_events)
  .enter()
  .append("li")
  .text(function(d) {
    return "Object 2";
});

在文件加载之前运行,此时 final_news_events 仍然是 [] 并且没有任何内容附加到 DOM.

如果将该代码包装在渲染函数中:

function renderList(newsEvents) {
  d3.select("body").append("ol").selectAll("text")
    .data(newsEvents)
    .enter()
    .append("li")
    .text(function(d) {
      return "Object 2";
  });
}

然后您可以在加载数据时调用该函数 — 从这里开始:

.get(function(error, rows) { 
  console.log(rows); 
  renderList(rows);
});

所以你甚至不需要设置 "global" final_news_events.