1. 程式人生 > 其它 >第1章 JavaScript簡介

第1章 JavaScript簡介

1. 探索JavaScript

  1. 嘗試少量JS程式碼,可以開啟瀏覽器的Web開發者工具(F12、Ctrl+Shift+I、Command+Option+I)
  2. 也可以下載Node後,開啟終端,輸入node並回車,輸入JS程式碼

2. Hello World

當需要執行長段JS程式碼時,可以將程式碼寫進JS檔案中,在node執行這個檔案或者將js檔案引入html檔案,適用url地址在瀏覽器開啟該html檔案


3. JavaScript之旅

  1. 第2章: 解釋JavaScript註釋、分號和Unicode字符集
  2. 第3章: 解釋JavaScript變數以及可以賦給這些變數的值
  3. 第4章: 表示式
  4. 第5章: 語句
  5. 第6章: 物件
  6. 第7章: 陣列
  7. 第8章: 函式
  8. 第9章: 面對物件程式設計
  9. 第10章: 模組
    展示檔案或指令碼中的JavvaScript程式碼如何使用其他檔案和指令碼中定義的JavaScript函式
  10. 第11章: JavaScript標準庫
    展示所有JavaScript程式都可以使用的內建函式和類,包括像對映、集合這樣重要的資料結構,還有用於文字模式匹配的正則表示式類,以及序列化JavaScript資料結構的函式,等等。
  11. 第12章: 迭代器與生成器
    解釋for/of迴圈的原理,以及如何定義可以在for/of中使用的類。該章還介紹生成器函式及yield語句。
  12. 第13章: 非同步JavaScript

    該章深入討論JavaScript的非同步程式設計,涵蓋回撥與事件、基於期約的API,以及asyncawait關鍵字雖然核心JavaScript語言並非非同步的,但瀏覽器和Node中的API預設都是非同步的。該章解釋適用這些API的技術。
  13. 第14章: 超程式設計
    介紹一些高階JavaScript特性,為其他JavaScript程式設計師編寫程式碼庫的讀者可能會感興趣。
  14. 第15章: 瀏覽器中的JavaScript
    介紹瀏覽器宿主環境,解釋瀏覽器如何執行JavaScript程式碼,涵蓋瀏覽器定義的大多數重要API。該章是迄今為止這本書中最長的一章。
  15. 第16章: Node伺服器端JavaScript

    介紹Node宿主環境,涵蓋基礎程式設計模型、資料結構和需要理解的最重要的API。
  16. 第17章: JavaScript工具和擴充套件
    涵蓋廣泛應用並有效提升開發者效率的工具及語言擴充套件。

4. 示例:字元頻率柱形圖

/**
 * This Node program reads text from standard input, computes the frequency
 * of each letter in that text, and displays a histogram of the most
 * frequently used characters. It requires Node 12 or higher to run.
 *
 * In a Unix-type environment you can invoke the program like this:
 *    node charfreq.js < corpus.txt
 */

// This class extends Map so that the get() method returns the specified
// value instead of null when the key is not in the map
class DefaultMap extends Map {
    constructor(defaultValue) {
        super();                          // Invoke superclass constructor
        this.defaultValue = defaultValue; // Remember the default value
    }

    get(key) {
        if (this.has(key)) {              // If the key is already in the map
            return super.get(key);        // return its value from superclass.
        }
        else {
            return this.defaultValue;     // Otherwise return the default value
        }
    }
}

// This class computes and displays letter frequency histograms
class Histogram {
    constructor() {
        this.letterCounts = new DefaultMap(0);  // Map from letters to counts
        this.totalLetters = 0;                  // How many letters in all
    }

    // This function updates the histogram with the letters of text.
    add(text) {
        // Remove whitespace from the text, and convert to upper case
        text = text.replace(/\s/g, "").toUpperCase();

        // Now loop through the characters of the text
        for(let character of text) {
            let count = this.letterCounts.get(character); // Get old count
            this.letterCounts.set(character, count+1);    // Increment it
            this.totalLetters++;
        }
    }

    // Convert the histogram to a string that displays an ASCII graphic
    toString() {
        // Convert the Map to an array of [key,value] arrays
        let entries = [...this.letterCounts];

        // Sort the array by count, then alphabetically
        entries.sort((a,b) => {              // A function to define sort order.
            if (a[1] === b[1]) {             // If the counts are the same
                return a[0] < b[0] ? -1 : 1; // sort alphabetically.
            } else {                         // If the counts differ
                return b[1] - a[1];          // sort by largest count.
            }
        });

        // Convert the counts to percentages
        for(let entry of entries) {
            entry[1] = entry[1] / this.totalLetters*100;
        }

        // Drop any entries less than 1%
        entries = entries.filter(entry => entry[1] >= 1);

        // Now convert each entry to a line of text
        let lines = entries.map(
            ([l,n]) => `${l}: ${"#".repeat(Math.round(n))} ${n.toFixed(2)}%`
        );

        // And return the concatenated lines, separated by newline characters.
        return lines.join("\n");
    }
}

// This async (Promise-returning) function creates a Histogram object,
// asynchronously reads chunks of text from standard input, and adds those chunks to
// the histogram. When it reaches the end of the stream, it returns this histogram
async function histogramFromStdin() {
    process.stdin.setEncoding("utf-8"); // Read Unicode strings, not bytes
    let histogram = new Histogram();
    for await (let chunk of process.stdin) {
        histogram.add(chunk);
    }
    return histogram;
}

// This one final line of code is the main body of the program.
// It makes a Histogram object from standard input, then prints the histogram.
histogramFromStdin().then(histogram => { console.log(histogram.toString()); });

注:在編譯器上使用node charfreq.js < charfreq.js會報錯,是因為編譯器終端選擇的是powershell而不是cmd,可以通過更改編譯器終端或使用cmd開啟程式碼來解決這個問題。


5. 小結

本書以自底向上的方式解釋JavaScript。這意味著要先從較低層次的註釋、識別符號、變數和型別講起,然後在此基礎上介紹表示式、語句、物件和函式。接著介紹更高層次的語言抽象,例如類和模組。本書的書名包含“權威”二字是認真的,接下來的章節對這門語言的解釋可能詳細得令人反感。然而,想要真正掌握JavaScript必須理解這些細節,希望你能花時間從頭到尾讀完這本書。不過,不要一上來就想著這樣做。假如某一節內容你怎麼也看不懂,可以先跳過去。等你對這門語言有了一個整體的瞭解時,可以再回來瞭解那些細節。