Chapter 1. Introduction(入門)
第一章沒有具體示例,只是交待了一些準備工作。
全書示例代碼模板:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="d3.js"></script>
<script>
function draw(data) {
"use strict";
// badass visualization code goes here
}
</script>
</head>
<body>
<script>
d3.json("data/some_data.json", draw);
</script>
</body>
</html>
注意:這裏的 D3 庫文件是舊版的(【 v2.8.0.zip 下載】【 v5.15.1.zip 下載】)
這裏出現了本書第一坑(小坑):如果使用的新版本,調用 d3.json()
要使用 Promise
寫法:
d3.json("data/some_data.json").then(draw);
此外,書中還提到了一個在用 JSON
存數據時值得借鑑的基本原則:
數據不要放在 JSON 的鍵上。
——Micha 黃金法則
不推薦寫法:
{
"bob": 20,
"alice": 23,
"drew": 30
}
推薦寫法:
[
{
"name": "bob",
"age": 20
},
{
"name": "alice",
"age": 23
},
{
"name": "drew",
"age": 30
}
]
這裏還提到一個方法,用於快速切換到正確的 JSON
寫法:d3.entries( objJSON )
,但沒有給出具體示例,這裏補全:
let oldData = {
"bob": 20,
"alice": 23,
"drew": 30
};
let newData = d3.entries(oldData);
// [{key: "bob", value: 20},
// {key: "alice", value: 23},
// {key: "drew", value: 30}]
newData = newData.map(e => ({name: e.key, age: e.value}));
// [{name: "bob", age: 20},
// {name: "alice", age: 23},
// {name: "drew", age: 30}]
// 對比 ES6 中的 Object.entries():
let dataES6 = Object.entries(oldData);
// [["bob", 20],
// ["alice", 23],
// ["drew", 30]]
dataES6 = dataES6.map(e => ({name: e[0], age: e[1]}))
// (same result)
P.S. 感覺 ES6 更好用點(好吧,畢竟是 2012 年的小冊子,要啥自行車啊?!?!。。。)
【填坑系列文章快速跳轉】
- 《Getting Started with D3》填坑之旅(一):開篇
- 《Getting Started with D3》填坑之旅(二):第一章(佔位)
- 《Getting Started with D3》填坑之旅(三):第二章(佔位)
- 《Getting Started with D3》填坑之旅(四):第三章(佔位)
- 《Getting Started with D3》填坑之旅(五):第四章(佔位)
- 《Getting Started with D3》填坑之旅(六):第五章(佔位)