前言
此次功能需求是:觀察每個參賽者「姓名長度的字元數」
取得資料
- 宣告 data 放回傳的資料用
- 宣告變數,起始值為0
- 以 axios 抓取 API 資料,執行
render()及pieChart()函式,分別為判斷字元及繪製圓餅圖
var apiUrl ="https://raw.githubusercontent.com/hexschool/hexschoolNewbieJS/master/data.json";
var data = [];
var underSix = 0;
var aboveSix = 0;
axios.get(apiUrl).then((response) => {
data = response.data;
// console.log(data);
render();
pieChart();
})
//除錯
.catch(function (error) {
// handle error
console.log(error);
});
判斷字元函式
function render() {
data.forEach((item) => {
//處理中文字元
if (item.name.replace(/[^\x00-\xff]/g,"xx").length <= 6) {
underSix += 1;
} else {
aboveSix += 1;
}
});
}
載入 C3.js 繪製圓餅圖
function pieChart() {
const chart = c3.generate({
data: {
columns: [
['參賽者姓名在6個(含)字元數以下', underSix],
['參賽者姓名在7個字元數以上', aboveSix]
],
type: "pie",
colors: {
'參賽者姓名在6個(含)字元數以下': "#29B6F6",
'參賽者姓名在7個字元數以上': "#F06292",
//前面放"完成率",後面指定顏色
},
}
});
}