--- tags: language --- JavaScript Language === * Book: * [The main reference: Eloquent JavaScript 3rd edition](https://eloquentjavascript.net/) * [JavaScript技術手冊](https://www.books.com.tw/products/0010839570) * Resource: * [JavaScript fundamental - Exercises, Practice, Solution](https://www.w3resource.com/javascript-exercises/fundamental/index.php) * [JavaScript 物件導向介紹](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript) * [深入了解物件模型](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Details_of_the_Object_Model) * [JavaScript Standard Style](https://standardjs.com/) * [JavaScript: The Hard Parts, v2](https://frontendmasters.com/courses/javascript-hard-parts-v2/?utm_source=newsletter&utm_medium=email&utm_campaign=jsweekly_hardpartsv2) * [重新認識 JavaScript 系列](https://ithelp.ithome.com.tw/users/20065504/ironman/1259) * Some target tool: * D3.js * Webpack * [puppetee: a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol](https://github.com/puppeteer/puppeteer) * Temp: * [HTML5 Canvas Drag and Drop Tutorial](https://konvajs.org/docs/drag_and_drop/Drag_and_Drop.html) * [JavaScript drag and drop, resizing, and multi-touch gestures for modern browsers ](https://interactjs.io/) * [Resizable Rectangles](https://bl.ocks.org/Herst/093ff9962405dd564ef58ad8af9544d0) * [Draggable SVG elements](http://www.petercollingridge.co.uk/tutorials/svg/interactive/dragging/) # Javascript Learning Framework * JS Introduction * JS Basic Syntax * JS Objact * JS & Browser * JS & HTML * D3.js * JS & Communication * Ajax * Node # [Node.js](https://hackmd.io/@L_VGP_ZqS2WG30NvJnde1g/SkzXoxOw8) # JS Introduction * What is JavaScript: * JavaScript是嵌入 HTML的程式設計語言,可以在多種Web瀏覽器上執行,屬於一種使用者端的應用程式,在瀏覽器上,利用 HTTP下載嵌入JavaScript的 HTML,就能在使用者端執行以 JavaScript 描述的應用程式。 * JavaScript has made modern web applications possible — applications with which you can interact directly without doing a page reload for every action. * JS是一種標準化程式語言: * 像C/C++ 一樣沒有辦法**下載和安裝**,只有規範 * JavaScript 所使用的規範(規格書)叫做 **ECMAScript** * 訂完規範後就由各種開發者去處理可以「執行 JavaScript」語法的引擎(執行環境),也就是**實作(runtime)** * JS runtime: * 瀏覽器端:各家公司都有發展自己的 JavaScript Runtime * 伺服器端:Node.js 最有名 * 反之:Python, java...等語言都有明確載點,是一群核心社群維護並持續修改後推出新版本 runtime * Run JS: * run JS code with HTML: * JavaScript in HTML: ```htmlembedded <script> document.write("<h1>This is a heading</h1>"); </script> ``` * JavaScript is a file: ```htmlembedded <script src="file_path/file.js" charset="utf-8"> </script> ``` * Example: Read d3.min.js & write some JS in HTML ```htmlembedded <!DOCTYPE html> <html> <head> <script src = "../d3.min.js"></script> </head> <body> <p>Cat</p> <p>Dog</p> <script> d3.select("body") .selectAll("p") .text("Hello, World!") </script> </body> </html> ``` * Note: * type: 設定指令碼語言的類型 * src: 指向外部連結檔案 * 瀏覽器會依照< script> 出現順序依次載入 * Chrome: * open Chrome * press ```Ctrl + Shift + j``` * the JavaScript console where you can write and test your code * Install Node.js: * Web 界非常實用的線上編譯:[jsFiddle - Online Editor for the Web](https://jsfiddle.net/) # JS Best Practice * Test: * [Fast, easy and reliable testing for anything that runs in a browser.](https://github.com/cypress-io/cypress) # JS Basic Syntax ## Basic Value, Type, operator: * Values: * A typical modern computer has more than 30 billion bits (3-4 G) in its volatile data storage (working memory) * To be able to work with such quantities of bits without getting lost, we must separate them into chunks that represent pieces of information. * In JS, those chunk are called **values**. * all values are made of bits * each value has a type that determines its role (numbers, text, function, and so on) * to create a value, you must merely invoke its name * every value has to has to be stored somewhere * Numbers: * values of the number type are numeric values. * JS uses 64 bits to store a single number value * ```Infinity``` and ```-Infinity```, which represent the positive and negative infinities * check:```Number.MAX_VALUE``` => ```1.7976931348623157e+308``` * check:```Number.MIN_VALUE``` => ```5e-324``` * over above range => Infinity or -Infinity * ```NaN```:stands for "not a number" (but it is number type) * ```0/0``` => ```NaN``` * ```Infinity - Infinity``` => ```NaN``` * Strings: * strings are used to represent text * they are written by enclosing their content in quotes: ``` 'string' `string` "string" ``` * ```"string".length``` => ```6``` * escaping:```\```+special word * JS uses 16 bits per string element * JS uses **Unicode** standard (universal character encoding standard) to deal with string * This standard assigns a number to virtually every character(include most human language) you would ever need * UTF-8(8-bit Unicode Transformation Format)是一種針對Unicode的可變長度字元編碼,也是一種字首碼。它可以用來表示Unicode標準中的任何字元,且其編碼中的第一個位元組仍與ASCII相容,這使得原來處理ASCII字元的軟體無須或只須做少部份修改,即可繼續使用。 * pair of quotes can embed other values ````half of 100 is ${100 / 2}```` * string only have **concatenates** operation by '+': ```"con" + "cat" + "ena" + "tes"``` * ```typeof```: output a type name(string value) of the value you give it * ```typeof 5``` => ```"number"``` * ```typeof "x"``` => ```"string"``` * Boolean values: * ```typeof true``` => ```"boolean"``` * ```3 > 2``` => ```true``` * ```"love" > "lo"``` => ```true``` * ```true + false``` => ```1``` * Note: ```NaN == NaN``` => ```false``` * NaN is supposed to denote the result of a nonsensical computation, and as such, it isn’t equal to the result of any other nonsensical computations. * Empty values: * the values are used to denote the absence of a meaningful value * they are themselves values, but they carry no information * ```null```: 表示唯一個空白物件 * ```typeof null``` => ```"object"``` * ```undefined```: 未初始化的值變數預設都是 undefined * ```typeof undefined``` => ```"undefined"``` * object: * 物件,可定義屬性和方法: ```javascript var persion = new Object(); persion.name = "eric"; persion.age = 20; persion.growUp = function(){ this.age += 1; } persion.growUp(); console.log(persion.age); //21 console.log(persion.name.length); //4 ``` * operators * operator only take one value is called unary operator, two is called binary operators * arithmetic operator: ```+(=) -(=) *(=) /(=) %(=) ++ --``` * comparing: ``` >(=) <(=) == != === !==``` * logical operators: * and : ``` &&``` * or : ```||``` * not : ```!``` * condition operators: * ```console.log(true ? 1: 0)``` => ```1``` * ```console.log(false ? 1: 0)``` => ```2``` * **type coercion** - Automatic type conversion: * JS accept almost any program you give it, such as: * ```8 * null``` => ```0``` * ```"5" - 1``` => ```4``` * ```"5" + 1``` => ```51``` * ```"string" * 2``` => ```NaN``` * test a value is not null or undefined: * ```null == undefined``` => ```true``` * ```null == ohter_value``` => ```fasle`` * When an operator is applied to the “wrong” type of value, JavaScript will quietly convert that value to the type it needs, using a set of rules that often aren’t what you want or expect. ## JS Program Structure: * Basic programming concept: * A fragment of code that produces a value is called an **expression**. * If an expression corresponds to a sentence fragment, a JavaScript **statement** corresponds to a full sentence. * A program is a list of statements. The simplest kind of statement is an expression with a semicolon after it. * ```10;``` , ```!false;``` * Bindings: * imagine bindings as tentacles, rather than boxes * ```let```:define a binding ```javascript let ten = 10; console.log(ten*ten); //100 ``` * ```=``` operator can change a binding at anywhere ```javascript let ten = 10; ten = 999; console.log(ten); //999 ``` * ```var``` variable: * the binding way before pre-2015 JS * almost do the same thing with ```let``` * ```const```: a constant bindings * **Environment**: * The collection of bindings and their values that exist at a given time is called the **environment**. * When a program starts up, this environment is not empty. It always contains bindings that are part of the language standard, and most of the time, it also has bindings that provide ways to interact with the surrounding system. * **function**: * A lot of the values provided in the default **environment** have the type **function**. * A function is a piece of program wrapped in a value. * Executing a function is called invoking, calling, or applying it. * You can call a function by putting parentheses after an expression that produces a function value. * Usually you’ll directly use the name of the binding that holds the function. * argument:The values between the parentheses are given to the program inside the function. * return value * define a function: ```javascript function name_to_bind_func(parameters){ //statement reutrn some_value; } name_to_bind_func = function(parameters){ //statement with some values return some_value; } const name_to_bind_func = function(parameters){ //statement with some values return some_value; } //Arrow function const multi = (x, y) => {return x*y;}; const square = x => {return x*x;}; //if one parameter const test = () => {reutrn "gg";}; /* * the => expression like : * “this input (the parameters) produces this result (the body) */ ``` * control flow: * if ```javascript if(condition){ //statement } else if (condition){ //statement } else { //statement } ``` * while ```javascript let number = 0; while (number <= 12){ console.log(number); number += 2; } ``` * for loops: ```javascript for (let number=0; number <= 12; number+=2){ console.log(number); if (number%8 == 0){ break; } } ``` # Aynchronous * What is aynchronous * ... * JS & aynchronous * Aynchronous is a foundational issue in JS because it is the basic behavior in internet. * Basic condition of aynchronous: * 阻斷:交出掌控權 * 事件佇列:持續追蹤 * 回呼函數:執行完後用函數形式回傳結果 # Promise * Resource * [JavaScript Info - Promise](https://javascript.info/promise-basics) * First Look: ``` let promise = new Promise(function(resolve, reject) { // executor (the producing code, "singer") }); ``` * new Promise * create a promise instance * a API bridge the executor (producer) and consumer * function(): * a executor (producer) * when get thing done, it need to hand out the result * resolve: * the consumer, a callback function * receive the result of executor and do what it need to do * reject: * the consumer * if executor meet some error, reject receive the error message # Data Relate * [PapaParse: Parse CSV with JavaScript](https://github.com/mholt/PapaParse) ## D3.js * [主要參考書籍: AI時代在網頁上資料視覺化:D3.js實作寶典](https://www.books.com.tw/products/0010803892) * [以 D3 為基礎的好用工具: plotly.js](https://plot.ly/javascript/) * D3.js 基本介紹: * 全名: Data-Driven Documents (資料驅動的文件) * 由資料來決定繪圖流程的程式設計模式 * D3是一個 JavaScript 的函數驅動程式,主要用來做資料視覺化 * Document 是指 DOM(Document Object Model),用於控制網頁元素 * D3允許使用者綁定任意資料到 DOM,透過資料操作網頁元素,建立可互動式的圖表 * 直接使用 HTML、SVG、Canvas 實現圖形相當繁瑣困難,D3已經封裝好相關函數,開發者能注重在版面配置和邏輯 * D3 版本: * v1.0.0: 2011.02.18 * v2.0.0: 2011.08.25 * v3.0.0: 2012.12.22 * 3.x 是目前最穩定且資源最多版本 * v4.0.0: 2016.06.29 * 4.x 模組化設計(變動大,和前版不相容),開始支援 HTML5 的 Canvas * v5.0.0: 2018.04 * 少量向後不兼容的改動 * D3 優勢(相較其他視覺化工具): * D3 較底層,但又可以使程式足夠簡潔 * D3 更像數學函式庫,但又支援繪圖 * D3 封裝很多操作,但又在開發者渴望控制的地方給足夠自由 * D3 重要特性: * 資料與 DMO 綁定成一體,圖形元素 DMO 裡含有資料讓變更資料後的重繪更容易實現 * 計算和繪圖獨立,在複雜狀況時可以表現的比較好 * 類似 JQuery 的鏈式語法 * 包含多種強大的演算法來處裡各種問題。 * 同時支援 SVG 和 Canvas(4.x) * 預備知識: * HTML: 超文字標記語言,用於設定網頁內容 * CSS:層疊樣式表,用於設定網頁樣式 * JavaScript: * DOM:文件物件模型,用於修改文件的內容和結構 * SVG:可縮放向量圖,HTML5 用於繪製向量圖的元素 * Canvas:HTML5 用於繪製純量圖(點陣圖)的元素 * Environment: * Download(D3.zip): * [v3.5.17](https://github.com/d3/d3/releases/tag/v3.5.17) * latest: download from https://d3js.org/ ### D3 Select Set & Data: * 資料綁定(Data-Join) 是 D3 的核心知識,主要解決2個問題: * 如何根據資料增加元素 * 當資料發生更新時,如何修改元素 * 選擇元素: * 元素指 HTML 或 SVG 中的一組標籤(tag),Ex: body, p, div, circle... * 選擇元素的方法1, 參數為 CSS 選擇器(建議): * ```select```: 傳回比對選擇器後的第一個元素 ```javascript d3.select("body"); //pick body d3.select("#important"); //pick id=important d3.select(".content"); //pick class=content ``` * ```selectAll```: 傳回比對選擇器後所有元素 ```javascript d3.selectAll("p"); d3.selectAll(".content"); d3.selectAll("ul li");// pick all li in ul ``` * 選擇元素的方法2, 參數是 DOM API 選擇的元素: ```javascript var important = document.getElementById("important"); d3.select(important); ``` * 選擇集物件(selection obj.): * d3.select & d3.seleceAll 回傳的物件稱為選擇集(selection),其是資料綁定的受體 * 後續增加/刪除/修改屬性都須用選擇集 * 基本狀態指令```.empty() .node() .size()``` ```htmlembedded <!DOCTYPE html> <html> <head> <script src="../package/d3/d3.min.js" charset="utf-8"></script> <title>D3.js Demo </title> </head> <body> <p> Paragraph 1 </p> <p> Paragraph 2 </p> <p> Paragraph 3 </p> <script> // binding a selection obj. let paragraphs = d3.selectAll("p"); console.log(paragraphs.empty()); //false console.log(paragraphs.node()); //<p> Paragraph 1</p> console.log(paragraphs.size());//3 </script> </body> </html> ``` ![](https://i.imgur.com/HHAJMrI.png) * 更動元素和屬性設定 ```htmlembedded <!DOCTYPE html> <html> <head> <script src="../package/d3/d3.min.js" charset="utf-8"></script> <title>D3.js Demo </title> </head> <body> <h1> The D3 selection operation!! </h1> <script> let width = 400; let height = 400; // add svg element in body let svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); // add circle in svg svg.append("circle") .attr("cx", "50px") .attr("cy", "50px") .attr("r", "50px") .attr("fill", "red"); </script> </body> </html> ``` ![](https://i.imgur.com/Nuj7Qdg.png) * 資料綁定: ```htmlembedded <!DOCTYPE html> <html> <head> <script src="../package/d3/d3.min.js" charset="utf-8"></script> </head> <body> <script> let dataset = [50, 43, 120, 87, 99, 167, 142]; let width = 400; let height = 400; let svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); let padding = { top:20, right:20, bottom:20, left:20}; let rectStep = 35; let rectWidth = 30; let rect = svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("fill", "steelblue") .attr("x", function(d,i){return padding.left + i*rectStep;} ) .attr("y", function(d){return height - padding.bottom - d;} ) .attr("width", rectWidth) .attr("height", function(d){return d;} ); let text = svg.selectAll("text") .data(dataset) .enter() .append("text") .attr("fill", "white") .attr("font-size", "14px") .attr("text-anchor", "middle") .attr("x", function(d,i){return padding.left + i*rectStep;} ) .attr("y", function(d){return height - padding.bottom - d;} ) .attr("dx", rectWidth/2) .attr("dy", "1em") .text( function(d){return d;} ); </script> </body> </html> ``` ![](https://i.imgur.com/1MEBAu0.png) ### Read-write file in D3: * [Importing local json file using d3.json does not work ](https://stackoverflow.com/questions/17214293/importing-local-json-file-using-d3-json-does-not-work) * If you're running in a browser like chrome, you cannot [load local files](https://stackoverflow.com/questions/371875/local-file-access-with-javascript). * [Python SimpleHTTPServer Tutorial With Example | HTTP Request Handler](https://appdividend.com/2019/02/06/python-simplehttpserver-tutorial-with-example-http-request-handler/) ```python3 -m http.server 9000``` ```htmlembedded <!DOCTYPE html> <html> <head> <script src="../../package/d3/d3.min.js" charset="utf-8"> </script> </head> <body> <script> d3.csv("morley.csv", function(data) { document.write("<h1>Read data!!</h1>"); for (var i=0; i<data.length; i++){ var Expt = data[i].Expt; var Run = data[i].Run; var Speed = data[i].Speed; console.log("Expt: " + Expt +"\n" + "Run: " + Run + "\n" + "Speed: "+ Speed); document.write("Expt: " + data[i].Expt + ", "+ "Run: " + data[i].Run + ", "+ "Speed: " + data[i].Speed + ", "+ "<br>"); } }); </script> </body> </html> ``` ![](https://i.imgur.com/hDxe84S.jpg) * Example: read json file of some polygons and distances endopints & show it by d3.js:: ```htmlembedded <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="../d3.min.js" charset="utf-8"> </script> <script src="../plotly-latest.min.js" charset="utf-8"> </script> </head> <body> <div id="graph" style="width:40%;height:700px;"></div> <script> d3.json("./data/poly.json", function(read_data) { let poly = read_data.poly; let line = read_data.line; let data = []; let width = 500; let height = 500; let svg = d3.select("#graph") .append("svg") .attr("width", width) .attr("height", height); for (let i=0; i<poly.length; i++){ let endpoint = []; for (let j=0; j<poly[i].x.length; j++){ endpoint[j]=[poly[i].x[j], poly[i].y[j]]; }; svg.append("polygon") .attr("points", endpoint) .attr("fill", "blue"); }; for (let i=0; i<line.length; i++){ svg.append("line") .attr("x1", line[i].x[0]) .attr("y1", line[i].y[0]) .attr("x2", line[i].x[1]) .attr("y2", line[i].y[1]) .attr("stroke", "red") .attr("stroke-dasharray", "2"); } }); </script> </body> </html> ``` ## Plotly.js * Example: read json file of some polygons and distances endopints by D3 & show it by plotly.js: ```htmlembedded <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="../d3.min.js" charset="utf-8"> </script> <script src="../plotly-latest.min.js" charset="utf-8"> </script> </head> <body> <div id="graph" style="width:40%;height:700px;"></div> <script> d3.json("./data/poly.json", function(read_data) { let poly = read_data.poly; let line = read_data.line; let data = []; for (let i=0; i<poly.length; i++){ let single_data = { mode: "lines", x: poly[i].x, y: poly[i].y, fill: 'toself', fillcolor: '#ab63fa', line: {color: '#ab63fa'}, text: "poly" + i, hoverinfo: 'text' } data.push(single_data); }; for (let i=0; i<line.length; i++){ let single_data = { mode: "lines", x: line[i].x, y: line[i].y, line: {color: 'rgb(0, 0, 255)', width: 1, dash: 'dot'}, text: "dis." + i, hoverinfo: 'text' } data.push(single_data); }; let layout_line = []; console.log(data); let layout = { title: 'Pixel Check!', xaxis: {range: [-10,200]}, yaxis: {range: [-10,300]}, shapes: layout_line, }; GRAPH = document.getElementById('graph'); Plotly.plot(GRAPH, data, layout); }); </script> </body> </html> ``` ... # JS & Communication * source: * [The AJAX Engine](https://www.mathertel.de/AJAXEngine/#view=Home) * Name come from : [Ajax: A New Approach to Web Applications](https://immagic.com/eLibrary/ARCHIVES/GENERAL/ADTVPATH/A050218G.pdf) * Ajax introduction: * Asynchronous JavaScript and XML * the method of exchanging data with a server, and updating parts of a web page – without reloading the entire page * Before: * synchronously transmitting client side request * user wait for server response * get a whole new html page from server * Ajax: * asynchronously transmitting client side request * user keep going to use browser * browser get response and using call back function to do some thing * ex: using call back function to manipulate DOM and update specific block * Ajax import parts: * 通訊協議: * XML :(Extensible Markup Language)擴展類型可標記語言。面向短期的臨時數據處理,面向光纖絡,是Soap的基礎。 * Soap :(Simple Object Access Protocol)簡單對象訪問協議。是XML Web Service的通信協議。當用戶通過UDDI找到你的WSDL描述文檔後,他可以通過SOAP調用你建立的Web服務中的一個或多個。 操作。SOAP是XML文檔形式的調用方法的規範,它可以支持不同的折疊接口,像HTTP(S)或SMTP。 * WSDL:(Web Services Description Language)WSDL文件是一個XML文檔,用於說明一組SOAP消息以及如何交換這些消息。大多數情況下由軟件自動生成和使用。 * 非同步:執行非同步的幾個重要本質條件: 1. 非阻塞(Non-Blocking): * 某任務進到比較慢的動作時(Ex:I/O),可讓其暫時交出掌控權。 * JS 和 Python 中,generator 的 yield 語法就有阻斷函數的效果,所以常被用來模擬非同步。 * 目前兩個語言都有 async/await 語法來作這件事。 2. 回呼函數(Callback Function): * 交出掌控權的任務,會藉由回呼函數來返回其原本該要 return 的值。 * 其實就是把未執行完的動作以函數的形式讓程式可以把資料傳回,也就是一個方便程式作業的溝通方式。 * JS 的 Promise 就是用 API 的方式來處理回呼函式太多後產生的困擾。 3. 事件迴圈(Even Loop):用來監控所有回傳值狀態。 * 抽象的來看就是有個類似 while loop 的迴圈去檢查回呼函式狀態。 * XMLHttpRequest * DOM 直接操作: * * There are so many methods can make asynchronous resquest, ```XMLHttpRequest``` is one of they.