d3.map()检索数据的问题

时间:2014-05-16 19:55:13

标签: javascript d3.js

ANSWER - nameById.get(id)

(来自Lars Kotthoff的评论)


尝试加载.tsv以返回状态名称但无法访问值。我已经删除了其他所有内容以显示我所缺少的内容。点击后我可以看到nameById中的数据但是尝试引用数据失败了。我试图在路上添加字符串,如“id _”+ d.id等...但没有运气。谢谢你的任何想法。

点击控制台输出 - 好奇第一个'{'之前的'o'是什么(对象?)

undefined
undefined
o {1: "Alabama", 2: "Alaska", 4: "Arizona", 5: "Arkansas", 6: "California"…}

显着的HTML:

<button id="but">click</button>

<script src="js/d3.v3.min.js"></script>
<script src="js/queue.v1.min.js"></script>
<script src="js/topojson.v1.min.js"></script>
<script>

d3.select('#but').on('click', function() {
    console.log(nameById[1]);
    console.log(nameById["1"]);
    console.log(nameById);
});

var nameById = d3.map();
queue()
    .defer(d3.tsv, "tsv/us-state-names.tsv", function(d) { nameById.set(d.id, d.name); })
    .await(ready);

function ready(error) {
    if (error) return console.error(error);
}
</script>

和.tsv - 像往常一样,从一个优秀的d3示例中复制:

id  code    name
1   AL  Alabama
2   AK  Alaska
4   AZ  Arizona
5   AR  Arkansas
6   CA  California
8   CO  Colorado
9   CT  Connecticut
10  DE  Delaware
11  DC  District of Columbia
12  FL  Florida
13  GA  Georgia
15  HI  Hawaii
16  ID  Idaho
17  IL  Illinois
18  IN  Indiana
19  IA  Iowa
20  KS  Kansas
21  KY  Kentucky
22  LA  Louisiana
23  ME  Maine
24  MD  Maryland
25  MA  Massachusetts
26  MI  Michigan
27  MN  Minnesota
28  MS  Mississippi
29  MO  Missouri
30  MT  Montana
31  NE  Nebraska
32  NV  Nevada
33  NH  New Hampshire
34  NJ  New Jersey
35  NM  New Mexico
36  NY  New York
37  NC  North Carolina
38  ND  North Dakota
39  OH  Ohio
40  OK  Oklahoma
41  OR  Oregon
42  PA  Pennsylvania
44  RI  Rhode Island
45  SC  South Carolina
46  SD  South Dakota
47  TN  Tennessee
48  TX  Texas
49  UT  Utah
50  VT  Vermont
51  VA  Virginia
53  WA  Washington
54  WV  West Virginia
55  WI  Wisconsin
56  WY  Wyoming
60  AS  America Samoa
64  FM  Federated States of Micronesia
66  GU  Guam
68  MH  Marshall Islands
69  MP  Northern Mariana Islands
70  PW  Palau
72  PR  Puerto Rico
74  UM  U.S. Minor Outlying Islands
78  VI  Virgin Islands of the United States

1 个答案:

答案 0 :(得分:2)

D3地图不是对象,并且行为方式不同。在这种情况下,您需要使用.get()

nameById.get(id)