ข้ามไปยังเนื้อหา
รายวิชา
  • 1 Getting started
    1.1

    โปรแกรมแรกของคุณ

    โปรแกรมคือชุดคำสั่งสำหรับคอมพิวเตอร์ ใน JavaScript แต่ละคำสั่งเรียกว่า statement และคอมพิวเตอร์จะรัน statements จากบนลงล่าง

    console.log(...) จะพิมพ์ค่าลงใน console ซึ่งเป็นพื้นที่ข้อความอยู่ใต้โค้ด:

    console.log("Hello, world!");
    console.log(7 * 6);   // 42
    
    • ข้อความต้องใส่ในเครื่องหมายคำพูด: "Hello" หรือ 'Hello'. แต่ตัวเลขไม่ต้อง
    • ปิดแต่ละ statement ด้วยเครื่องหมายคั่นวรรค ;. JavaScript มักจะเดาได้ว่าขาดตรงไหน แต่การเขียนให้ชัดเจนก็ดีกว่า
    • JavaScript แยกตัวพิมพ์ใหญ่และเล็ก: console.log ใช้ได้, Console.Log ใช้ไม่ได้

    console.log สามารถพิมพ์หลายค่าพร้อมกันได้ โดยวางช่องว่างหนึ่งช่องระหว่างแต่ละค่า:

    console.log("Total:", 3 + 4);   // Total: 7
    console.log(1, 2, 3);           // 1 2 3
    
    1.2

    Comments & code style

    คอมเมนต์คือหมายเหตุสำหรับมนุษย์ JavaScript จะมองข้ามเมื่อโปรแกรมทำงาน

    // A one-line comment starts with two slashes.
    console.log("This line runs");   // a comment can follow code
    
    /* A block comment
       can cover several lines. */
    console.log("So does this one");
    

    Good style makes code easy to read:

    • ย่อบรรทัดภายใน { } ลงมาสองหรือสี่ช่อง และทำแบบเดียวกันทุกครั้ง
    • ตั้งชื่อตัวแปรให้บอกถึงสิ่งที่เก็บไว้: total, ไม่ใช่ t.
    • ชื่อตัวแปรใน JavaScript ใช้รูปแบบ camelCase: firstName, scoreTotal.
    // Work out the area of a rectangle
    const width = 4;
    const height = 3;
    console.log(width * height);   // 12
    

    ข้อผิดพลาดที่พบบ่อย

    • ข้อความต้องใช้เครื่องหมายคำพูดคู่กัน: "Hi' ถือว่าผิด
    • console.log ต้องพิมพ์ตัวพิมพ์เล็กทั้งหมด: Console.log และ console.Log ถือว่าผิด
    • ทุกอย่างหลังจาก // บนบรรทัดเดียวจะถูกมองข้าม ดังนั้น // console.log(x) จึงไม่พิมพ์อะไรออกมา
  • 2 Values, variables & types
    2.1

    let and const

    A variable 变量 is a named box that holds a value. Make one with let or const, then use its name:

    let score = 10;
    score = score + 5;      // let: the value can change
    console.log(score);     // 15
    
    const name = "Mei";     // const: the name cannot be reassigned
    console.log(name);      // Mei
    
    • = means assign 赋值: work out the right side, then store it in the box on the left.
    • Use const by default. Use let only when the value must change later.
    • Reassigning a const is an error: name = "Tom" is not allowed. A const object or array can still have its contents changed.
    2.2

    Numbers & maths

    These examples use the number type for whole and decimal values. BigInt is a separate integer type. The arithmetic operators 运算符 are:

    Operator Meaning Example Result
    + - add, subtract 7 - 2 5
    * / multiply, divide 7 / 2 3.5
    % remainder 余数 7 % 2 1
    ** power 2 ** 3 8
    console.log(7 / 2);              // 3.5
    console.log(Math.floor(7 / 2));  // 3   (whole-number division)
    console.log(7 % 2);              // 1   (odd numbers leave 1)
    console.log(2 + 3 * 4);          // 14  (* before +)
    console.log((2 + 3) * 4);        // 20
    
    Seven dots grouped into three pairs with one dot left over, beside Math.floor of 7 over 2 equals 3, 7 percent 2 equals 1 and 7 over 2 equals 3.5
    Seven shared into pairs: three whole pairs, one left over.

    Math holds useful functions:

    console.log(Math.round(2.5));    // 3
    console.log(Math.max(4, 9, 2));  // 9
    console.log(Math.sqrt(49));      // 7
    
    • Math.random() gives a random 随机 number from 0 up to (not including) 1. Math.floor(Math.random() * 6) + 1 is a dice roll from 1 to 6.
    • Decimals are stored in binary, so 0.1 + 0.2 prints 0.30000000000000004. Round a result before you show it: (0.1 + 0.2).toFixed(2) is "0.30".
    2.3

    Types & conversion

    Every value has a type 类型. typeof tells you which:

    console.log(typeof 42);         // number
    console.log(typeof "42");       // string
    console.log(typeof true);       // boolean
    console.log(typeof undefined);  // undefined
    
    • A variable made with let x; and no value is undefined.
    • null means "no value", set on purpose.

    + with a string joins instead of adding, so convert 转换 text to a number first:

    console.log("5" + 1);           // 51  (joined)
    console.log(Number("5") + 1);   // 6   (added)
    console.log(parseInt("12px"));  // 12  (reads the number at the start)
    console.log(String(9) + "!");   // 9!
    
    • A text that is not a number gives NaN ("not a number"): Number("abc") is NaN.
    • -, * and / convert text to a number by themselves ("6" * 2 is 12), but do not rely on it: convert on purpose.

    Common mistakes

    • = assigns; it does not compare. Comparing uses === (topic 4).
    • "5" + 1 is "51". Convert input with Number(...) before doing maths with it.
    • Math.round(2.5) is 3, but Math.round(-2.5) is -2: it rounds halves up, towards the larger number.
  • 3 สตริง (Strings)
    3.1

    ตัวอักษร & ความยาว

    ข้อความคือตัวอักษรที่ใส่ในเครื่องหมายคำพูด สำหรับตัวอักษรพื้นฐาน แต่ละตัวอักษรมีตำแหน่งเดียวคือดัชนี; ดัชนีแรกคือ 0 JavaScript นับหน่วยโค้ด UTF-16: อีโมจิอาจใช้สองตำแหน่ง

    const word = "Script";
    console.log(word.length);     // 6
    console.log(word[0]);         // S
    console.log(word[2]);         // r
    console.log(word.at(-1));     // t  (counts back from the end)
    console.log(word[word.length - 1]);   // t
    
    • ดัชนีตัวสุดท้ายคือ length - 1. word[6] คือ undefined, ไม่ใช่ข้อผิดพลาด.
    • String เป็นค่าที่ไม่สามารถแก้ไขได้: word[0] = "s" ไม่สามารถเปลี่ยน string ได้และจะเกิด TypeError ใน strict mode ควรสร้าง string ใหม่แทน

    เชื่อม string ด้วย + ซึ่งเรียกว่าการต่อ string (concatenation):

    const first = "Ada";
    const last = "Lovelace";
    console.log(first + " " + last);   // Ada Lovelace
    
    3.2

    String methods

    เมทโธดคือฟังก์ชันที่เป็นส่วนหนึ่งของค่าหนึ่งๆ เรียกมันด้วยจุด เมทโธดของ string จะส่งกลับค่า ใหม่ และค่าเดิมจะไม่เปลี่ยนแปลง

    const city = "  Hong Kong ";
    console.log(city.trim());                 // Hong Kong
    console.log(city.trim().toUpperCase());   // HONG KONG
    console.log(city.length);                 // 12  (the spaces are still there)
    
    Method ความหมาย ตัวอย่าง ผลลัพธ์
    .toUpperCase() / .toLowerCase() เปลี่ยนกรณี "Hi".toLowerCase() "hi"
    .trim() ลบช่องว่างด้านหน้าและท้าย " hi ".trim() "hi"
    .includes(t) มี t อยู่หรือไม่? "cat".includes("a") true
    .indexOf(t) ตำแหน่งแรก ของ t หรือ -1 "cat".indexOf("t") 2
    .slice(a, b) ตัวอักษรตั้งแต่ a ถึง (ไม่รวม) b "Script".slice(0, 3) "Scr"
    .split(sep) แยกออกเป็นอาร์เรย์ "a,b,c".split(",") ["a","b","c"]
    .replace(a, b) เปลี่ยน a ตัวแรกเป็น b "cat".replace("c", "b") "bat"
    const email = "[email protected]";
    const at = email.indexOf("@");
    console.log(email.slice(0, at));          // mei
    console.log(email.slice(at + 1));         // school.org
    console.log(email.split("@"));            // ["mei","school.org"]
    
    3.3

    ลิเตอรัลเทมเพลต

    Template literal คือ string ที่เขียนระหว่าง backtick (บนคีย์บอร์ดส่วนใหญ่คือปุ่มทางซ้ายมือของ 1) ใส่ expression ใดๆ ไว้ภายใน ${ } แล้วค่าของมันจะถูกวางลงในข้อความ:

    const name = "Mei";
    const age = 17;
    console.log(`${name} is ${age} years old.`);   // Mei is 17 years old.
    console.log(`Next year: ${age + 1}`);          // Next year: 18
    
    • Backtick ยังสามารถรองรับข้อความหลายบรรทัดได้
    • อ่านง่ายกว่าการใช้ + หลายตัว: เปรียบเทียบ "Hi " + name + "!" กับ `Hi ${name}!`
    const price = 4.5;
    console.log(`Two cost $${(price * 2).toFixed(2)}`);   // Two cost $9.00
    

    ข้อผิดพลาดที่พบบ่อย

    • ${ } ใช้ได้เฉพาะภายใน backtick เท่านั้น ใน "Hi ${name}" ข้อความจะถูกพิมพ์ออกมาตามตัวอักษรที่พิมพ์ไว้
    • เมทโธดไม่เปลี่ยน string: การเรียก city.trim() บนบรรทัดเดียวโดยไม่มีสิ่งอื่นทำไม่ได้ผล เก็บผลลัพธ์ไว้: const clean = city.trim();
    • slice(a, b) จะหยุด ก่อน b เหมือนกับว่าดัชนีตัวสุดท้ายคือ length - 1
  • 4 Decisions
    4.1

    บูลีนและการเปรียบเทียบ

    布尔ีนมีเพียง true หรือ false การเปรียบเทียบให้ผลลัพธ์เป็น布尔ีน:

    ตัวดำเนินการ ความหมาย ตัวอย่าง ผลลัพธ์
    === เท่ากัน (มีค่าเหมือนกันและมีประเภทเดียวกัน) 5 === 5 true
    !== ไม่เท่ากับ 5 !== 3 true
    < > น้อยกว่า, มากกว่า 2 > 7 false
    <= >= อย่างมาก, อย่างน้อย 7 >= 7 true
    console.log(5 === 5);     // true
    console.log(5 === "5");   // false  (a number is not a string)
    console.log(5 == "5");    // true   (== converts first: avoid it)
    
    • ใช้ === และ !== เสมอ ส่วน == ที่เก่ากว่าจะแปลงชนิดข้อมูลก่อนแล้วให้ผลลัพธ์ที่แปลกประหลาด

    สำหรับเงื่อนไข Boolean ให้ใช้ตัวดำเนินการทางตรรกะด้านล่าง เมื่อใช้กับค่าอื่น ๆ && และ || จะคืนค่า operands ของตัวเองอย่างใดอย่างหนึ่ง; มันไม่จำเป็นต้องคืนค่า Boolean เสมอไป:

    • && (และ): เป็นจริงก็ต่อเมื่อ ทั้งสอง ด้านเป็นจริงเท่านั้น
    • || (หรือ): เป็นจริงหาก อย่างน้อยด้านหนึ่ง เป็นจริง
    • ! (ไม่): เปลี่ยน true เป็น false และกลับคืนมาอีกครั้ง
    const age = 15;
    console.log(age >= 13 && age <= 19);   // true   (a teenager)
    console.log(age < 5 || age > 65);      // false
    console.log(!(age > 18));              // true
    
    4.2

    if / else if / else

    คำสั่ง if จะรันบล็อกโค้ดเมื่อเงื่อนไขมีค่าเป็น truthy (ถูกพิจารณาว่าเป็นจริง) สำหรับเงื่อนไข Boolean หมายความว่าค่านั้นคือ true else if จะทดสอบเงื่อนไขอื่น; else จะจับทุกสิ่งที่เหลืออยู่:

    const mark = 72;
    if (mark >= 80) {
      console.log("A");
    } else if (mark >= 60) {
      console.log("B");
    } else {
      console.log("C");
    }
    // prints B
    
    • JavaScript จะตรวจสอบเงื่อนไขจากบนลงล่างและรัน เฉพาะสาขาที่เป็นจริงแรกเท่านั้น
    • เงื่อนไขอยู่ภายในวงเล็บ round brackets; โค้ดที่จะรันอยู่ภายใน curly braces { }

    ดังนั้นลำดับจึงสำคัญ วางการทดสอบที่เข้มงวดที่สุดไว้ก่อน:

    const temp = 35;
    if (temp > 30) {
      console.log("hot");
    } else if (temp > 20) {
      console.log("warm");   // skipped: the first branch already ran
    }
    // prints hot
    
    4.3

    สวิตช์

    A switch เปรียบเทียบค่าหนึ่งเทียบกับหลายกรณีคงที่ มันดูสะอาดกว่าการใช้ else if ยาวๆ เมื่อทุกการทดสอบคือ "มันเท่ากับ…หรือไม่?":

    const day = "Sat";
    switch (day) {
      case "Sat":
      case "Sun":
        console.log("weekend");
        break;
      case "Fri":
        console.log("nearly there");
        break;
      default:
        console.log("school day");
    }
    // prints weekend
    
    • switch เปรียบเทียบด้วย === ดังนั้น case 1: จึงไม่ตรงกับ string "1"
    • break จะจบ switch หากไม่มีโค้ดนี้ โค้ดจะ ไหลผ่าน ไปยัง case ถัดไป
    • default ทำงานเมื่อไม่มี case ตรงกับเงื่อนไข เหมือนกับ final else
    • สองกรณีที่ไม่มีโค้ดระหว่างกันจะแบ่งปันโค้ดเดียวกัน เช่น "Sat" และ "Sun" ทำในที่นี้

    ข้อผิดพลาดที่พบบ่อย

    • if (x = 5) เป็นการกำหนดค่าแทนที่จะเป็นการเปรียบเทียบ ทำให้การทดสอบเป็นจริงเสมอ ควรเขียน if (x === 5)
    • if (age > 13 && < 19) คือข้อผิดพลาด: ซ้ำชื่อตัวแปร ซึ่งควรใช้ age > 13 && age < 19
    • การขาด break ใน switch จะทำให้รัน case ถัดไปด้วย
  • 5 Loops
    5.1

    ลูป for

    สามส่วนของลูป for และลำดับการทำงาน

    ลูปซ้ำชุดโค้ดหนึ่งครั้ง ลูป for เหมาะที่สุดเมื่อคุณทราบจำนวนครั้งที่ต้องการ-repeat beforehand Its brackets hold three parts, separated by semicolons:

    for (let i = 1; i <= 3; i++) {
      console.log(i);
    }
    // 1
    // 2
    // 3
    
    1. เริ่มต้น: let i = 1 ทำงานครั้งเดียว ก่อนเริ่มลูป
    2. เงื่อนไข: i <= 3 ถูกตรวจสอบก่อนทุกรอบ; ลูปจะหยุดเมื่อเป็นเท็จ
    3. ขั้นบันได: i++ (เพิ่ม 1 เข้ากับ i) ทำงานหลังทุกรอบ

    แต่ละรอบผ่านลูปคือหนึ่งรอบวนเวียน เปลี่ยนขั้นบันไดเพื่อนับด้วยวิธีอื่น:

    let line = "";
    for (let i = 10; i > 0; i -= 3) {
      line += i + " ";
    }
    console.log(line);   // 10 7 4 1
    

    รูปแบบตัวสะสมสร้างตัวแปร ก่อน ลูป และอัปเดตในทุกรอบ:

    let total = 0;
    for (let n = 1; n <= 5; n++) {
      total += n;          // the same as total = total + n
    }
    console.log(total);    // 15
    
    5.2

    ลูป while

    ลูป while ซ้ำจนกว่าเงื่อนไขจะเป็นจริง ใช้เมื่อไม่ทราบจำนวนรอบล่วงหน้า:

    let money = 100;
    let years = 0;
    while (money < 200) {
      money = money * 1.1;   // 10% interest each year
      years++;
    }
    console.log(years);      // 8
    
    • เงื่อนไขถูกตรวจสอบ ก่อน ทุกรอบ ดังนั้นบอดี้อาจทำงานได้ 0 ครั้ง
    • หากเงื่อนไขเป็นจริงตลอดและไม่เจอ break หรือการออกอื่น ๆ จะได้ลูปไม่มีที่สิ้นสุด (กด Stop หากเกิดกรณีนี้)
    5.3

    for...of, break & continue

    for...of เข้าถึงทุกองค์ประกอบของอาร์เรย์ (หรือทุกตัวอักษรของสตริง) ตามลำดับ โดยไม่ต้องจัดการดัชนี:

    const fruits = ["apple", "kiwi", "plum"];
    for (const fruit of fruits) {
      console.log(fruit.toUpperCase());
    }
    // APPLE
    // KIWI
    // PLUM
    

    break จะออกจาก loop ทันที; continue จะข้ามส่วนที่เหลือของการวนรอบนี้และไปยังรอบถัดไป:

    const marks = [55, 80, -1, 90];
    let sum = 0;
    for (const m of marks) {
      if (m < 0) {
        break;            // -1 means "end of the data"
      }
      if (m < 60) {
        continue;         // skip a fail, keep looping
      }
      sum += m;
    }
    console.log(sum);     // 80
    

    ข้อผิดพลาดที่พบบ่อย

    • ข้อผิดพลาด off-by-one: i < 3 ทำงานสำหรับ 0, 1, 2; i <= 3 ทำงานเพิ่มอีก 1 รอบ นับจำนวนรอบให้ถูกต้อง
    • การตั้งค่าผลรวมภายในลูป: let total = 0; ต้องอยู่ ก่อน ลูป มิฉะนั้นจะถูกรีเซ็ตทุกรอบ
    • ลูป while จะรันตลอดหากเงื่อนไขเป็นจริงและไม่มีการออก
  • 6 ฟังก์ชัน
    6.1

    Parameters & return

    A function 函数 is a reusable piece of code. A function declaration gives it a name, which you can use to call 调用 it:

    function greet(name) {
      return `Hello, ${name}!`;
    }
    
    console.log(greet("Mei"));   // Hello, Mei!
    console.log(greet("Tom"));   // Hello, Tom!
    
    • name is a parameter 参数: a variable that receives a value when the function is called.
    • "Mei" is the argument 实参: the actual value passed in.
    • return sends a value back to the caller and ends the function at once.

    A regular function that reaches its end without returning a value gives back undefined. So return the answer, and let the caller decide whether to print it:

    function area(width, height) {
      return width * height;
    }
    
    const a = area(4, 3);
    console.log(a + 1);          // 13  (a returned value can be used again)
    
    6.2

    Arrow functions

    An arrow function 箭头函数 is a shorter way to write a function. Store it in a const:

    const square = (n) => n * n;
    const add = (a, b) => a + b;
    
    console.log(square(5));      // 25
    console.log(add(2, 3));      // 5
    
    • With one expression after =>, its value is returned without writing return.
    • With curly braces you need return again:
    const grade = (mark) => {
      if (mark >= 50) {
        return "pass";
      }
      return "fail";
    };
    console.log(grade(64));      // pass
    

    Arrow functions are often passed to other functions, as you will see with map and filter in topic 7.

    6.3

    Scope

    The scope 作用域 of a variable is the part of the code that can see it. A variable made with let or const inside { } is accessible in that block and its nested scopes. A nested function can keep access after the outer call returns:

    const level = "global";
    
    function show() {
      const inside = "local";
      console.log(level);        // global  (outer variables are visible)
      console.log(inside);       // local
    }
    
    show();
    console.log(typeof inside);  // undefined  (inside does not exist out here)
    
    • A variable made inside a function is a local variable 局部变量; each call gets a fresh one.
    • Pass values in as parameters and get results out with return, instead of changing outer variables from inside a function.

    Common mistakes

    • Forgetting return: the function works out the answer, then gives back undefined.
    • Calling without brackets: greet is the function itself; greet("Mei") runs it.
    • Printing inside the function and printing its result prints twice, or prints undefined.
  • 7 Arreglo
    7.1

    Making & changing arrays

    An array 数组 holds a list of values in order, inside square brackets. Each item is an element 元素, and the first index is 0:

    const scores = [72, 88, 95];
    console.log(scores[0]);        // 72
    console.log(scores.length);    // 3
    scores[1] = 90;                // change one element
    console.log(scores);           // [72,90,95]
    
    • const stops you giving scores a whole new array, but you can still change what is inside it.
    • Reading past the end gives undefined: scores[3] is undefined.

    Add and remove at the end with push and pop:

    const queue = ["Ann", "Ben"];
    queue.push("Cai");             // add to the end
    console.log(queue);            // ["Ann","Ben","Cai"]
    const last = queue.pop();      // remove from the end and return it
    console.log(last);             // Cai
    console.log(queue.length);     // 2
    

    An array can hold arrays. That makes a grid, read with two indexes, row first:

    const grid = [
      [1, 2, 3],
      [4, 5, 6],
    ];
    console.log(grid[1][2]);       // 6  (row 1, column 2)
    
    7.2

    map, filter & reduce

    English

    These methods take a function and apply it to the array elements. They return a new array (or value) without themselves replacing the original items. The function you pass in can still change the original array or its objects:

    • map makes a new array by changing every element.
    • filter keeps only the elements for which the function returns true.
    • reduce combines all the elements into one value, such as a total.
    const prices = [4, 10, 25];
    const withTax = prices.map((p) => p * 1.1);
    console.log(withTax.map((p) => p.toFixed(2)));   // ["4.40","11.00","27.50"]
    
    const cheap = prices.filter((p) => p < 20);
    console.log(cheap);                              // [4,10]
    
    const total = prices.reduce((sum, p) => sum + p, 0);
    console.log(total);                              // 39
    

    In reduce, sum is the accumulator. It starts at the last argument (0) and takes the function's result after each element.

    7.3

    Searching & sorting

    English
    sort() with no compare function sorts numbers as text
    Method Gives back Example with [5, 8, 2] Result
    .includes(x) true or false .includes(8) true
    .indexOf(x) the first index of x, or -1 .indexOf(2) 2
    .find(f) the first element where f is true .find((n) => n > 6) 8
    .findIndex(f) its index, or -1 .findIndex((n) => n > 6) 1

    sort puts the elements in order. With no function, it sorts them as text, so numbers come out in the wrong order:

    const nums = [10, 9, 100, 1];
    console.log([...nums].sort());                   // [1,10,100,9]   (as text!)
    console.log([...nums].sort((a, b) => a - b));    // [1,9,10,100]
    console.log([...nums].sort((a, b) => b - a));    // [100,10,9,1]
    
    • The compare function returns a negative number when a should come first, and a positive number when b should.
    • sort changes the array itself. [...nums] makes a copy first, so nums keeps its order.

    Common mistakes

    • The last element is arr[arr.length - 1], not arr[arr.length].
    • map and filter do not change the array: store their result.
    • nums.sort() on numbers sorts them as text. Pass (a, b) => a - b.
  • 8 ออบเจกต์ (Objects)
    8.1

    Objects & properties

    An object 对象 groups related values under names. Each name-and-value pair is a property 属性. The name is called the key 键:

    const pupil = {
      name: "Mei",
      age: 17,
      form: "11A",
    };
    console.log(pupil.name);       // Mei
    console.log(pupil["form"]);    // 11A  (bracket form, with the key as a string)
    
    • Read a property with a dot (pupil.age) or with brackets (pupil["age"]). Use brackets when the key is in a variable: pupil[field].
    • A key that does not exist gives undefined.

    Change a property, or add a new one, by assigning to it:

    const pupil = { name: "Mei", age: 17 };
    pupil.age = 18;                // change
    pupil.house = "Red";           // add
    console.log(pupil);            // {"name":"Mei","age":18,"house":"Red"}
    
    8.2

    Arrays of objects

    A list of records 记录 is an array of objects. Combine it with the array methods from topic 7:

    const pupils = [
      { name: "Mei", mark: 88 },
      { name: "Tom", mark: 64 },
      { name: "Sara", mark: 95 },
    ];
    
    const passed = pupils.filter((p) => p.mark >= 70);
    console.log(passed.map((p) => p.name));            // ["Mei","Sara"]
    
    const best = [...pupils].sort((a, b) => b.mark - a.mark)[0];
    console.log(`${best.name} has the top mark`);       // Sara has the top mark
    

    To total a property, use reduce or a loop:

    const pupils = [{ mark: 88 }, { mark: 64 }, { mark: 95 }];
    let sum = 0;
    for (const p of pupils) {
      sum += p.mark;
    }
    console.log((sum / pupils.length).toFixed(1));      // 82.3
    
    8.3

    Looping over an object

    Object.keys gives an array of the keys, and Object.entries gives [key, value] pairs, so you can loop over them:

    const stock = { pens: 12, rulers: 0, books: 5 };
    
    console.log(Object.keys(stock));             // ["pens","rulers","books"]
    
    for (const [item, count] of Object.entries(stock)) {
      if (count === 0) {
        console.log(`${item}: sold out`);
      }
    }
    // rulers: sold out
    

    An object is a good counter 计数器: use each thing you count as a key.

    const words = ["red", "blue", "red", "red"];
    const counts = {};
    for (const w of words) {
      counts[w] = (counts[w] || 0) + 1;   // 0 the first time the key is seen
    }
    console.log(counts);                  // {"red":3,"blue":1}
    

    Common mistakes

    • pupil.field looks for a key called field. When the key is in a variable, write pupil[field].
    • A comma goes between properties, not a semicolon: { name: "Mei", age: 17 }.
    • for...of cannot loop over an object directly. Loop over Object.keys(...) or Object.entries(...).
  • 9 ข้อผิดพลาด
    9.1

    อ่านข้อความข้อผิดพลาด

    เมื่อ JavaScript ไม่สามารถดำเนินการต่อไปได้ มันจะหยุดและแสดงข้อความข้อผิดพลาด คำแรกจะระบุประเภทของข้อผิดพลาด ส่วนที่เหลือจะบอกสิ่งที่เกิดขึ้นผิดและตำแหน่งที่ควรตรวจสอบ อ่านข้อความนั้นแล้วดูที่บรรทัดที่ระบุถึง

    SyntaxError: missing ) after argument list
    ReferenceError: totl is not defined
    TypeError: Cannot read properties of undefined (reading 'length')
    
    ข้อผิดพลาด ความหมาย สาเหตุทั่วไป
    SyntaxError โค้ดไม่ถูกต้องตามหลักไวยากรณ์ ทำให้ไม่มีอะไรทำงานได้ ขาดวงเล็บหรือเครื่องหมายคำพูด
    ReferenceError ชื่อที่ไม่มีการนิยามไว้ ข้อผิดพลาดในการสะกด: totl แทนที่จะเป็น total
    TypeError ค่ามีประเภทที่ไม่ตรงกับสิ่งที่ทำ การใช้ .length กับ undefined

    ข้อความอาจแตกต่างกันไปในแต่ละเบราว์เซอร์ แต่ชื่อของข้อผิดพลาดจะเหมือนกัน โปรแกรมนี้จะจับข้อผิดพลาดแต่ละชนิดเพื่อให้สามารถพิมพ์ชื่อออกมาได้:

    try {
      const total = 5;
      console.log(totl);
    } catch (e) {
      console.log(e.name);           // ReferenceError
    }
    
    try {
      const pupil = undefined;
      console.log(pupil.length);
    } catch (e) {
      console.log(e.name);           // TypeError
    }
    

    ความผิดพลาดบางชนิดไม่แสดงข้อความข้อผิดพลาดเลย มีเพียงคำตอบที่ผิด: ข้อผิดพลาดทางตรรกะ เพื่อหาข้อผิดพลาดนี้ ให้พิมพ์ค่าต่างๆ ระหว่างทางด้วย console.log แล้วตรวจสอบเอง

    9.2

    try, catch & throw

    โค้ดที่อาจเกิดข้อผิดพลาดจะอยู่ในบล็อก try หากมีข้อผิดพลาดเกิดขึ้น JavaScript จะข้ามไปยัง catch แทนที่จะหยุดทำงาน และ e จะเก็บข้อมูลข้อผิดพลาดนั้นไว้:

    try {
      JSON.parse("{not valid}");
      console.log("parsed");         // skipped
    } catch (e) {
      console.log("Could not read the data");
    }
    console.log("The program carries on");
    

    โค้ดของคุณสามารถสร้างข้อผิดพลาดด้วย throw สิ่งนี้ช่วยให้ฟังก์ชันปฏิเสธข้อมูลที่ไม่เหมาะสมได้อย่างชัดเจน แทนที่จะส่งคำตอบที่ผิดออกมา:

    function average(list) {
      if (list.length === 0) {
        throw new Error("the list is empty");
      }
      return list.reduce((s, x) => s + x, 0) / list.length;
    }
    
    console.log(average([4, 6]));    // 5
    try {
      average([]);
    } catch (e) {
      console.log(`Error: ${e.message}`);   // Error: the list is empty
    }
    
    • new Error("…") จะเกิดerror ที่มี message เป็นข้อความของคุณ.
    • ใช้เฉพาะ try กับโค้ดที่อาจล้มเหลวจริง เช่น การอ่านข้อมูล อย่าใช้เพื่อปิดบังความผิดพลาดในโค้ดของคุณเอง

    ข้อผิดพลาดที่พบบ่อย

    • การข้ามข้อความส่วน บรรทัดแรก จะระบุประเภทของข้อผิดพลาดและสิ่งที่ผิดปกติ ให้เริ่มต้นอ่านจากบรรทัดนี้
    • การใช้ catch ที่ไม่ทำอะไรเลย (catch (e) {}) จะซ่อนปัญหา: อย่างน้อยก็ควรพิมพ์ e.message ออกมา
    • throw "text" ทำงานได้ แต่ throw new Error("text") ยังบันทึกตำแหน่งที่เกิดข้อผิดพลาดด้วย

เข้าสู่ระบบหรือสร้างบัญชี

IGCSE, A-Level & AP