d3.map() 检索数据时出现问题
2014-05-16
118
答案 - 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个回答
D3 地图不是对象,行为方式也不同。在这种情况下,您需要使用
.get()
:
nameById.get(id)
Lars Kotthoff
2014-05-16