본문 바로가기
과목
  • 1 초기 설정
    1.1

    첫 번째 프로그램

    A program 程序 is a list of instructions for the computer. In JavaScript, each instruction is a statement 语句, and the computer runs the statements from top to bottom.

    console.log(...) prints a value in the console 控制台, the text area under the code:

    console.log("Hello, world!");
    console.log(7 * 6);   // 42
    
    • Text goes inside quotes: "Hello" or 'Hello'. Numbers do not.
    • End each statement with a semicolon ;. JavaScript can often guess where one is missing, but writing it is clearer.
    • JavaScript is case-sensitive 区分大小写: console.log works, Console.Log does not.

    To put a quote mark inside text, use the other kind of quote around it. A backslash 反斜杠 starts a special character: \n starts a new line.

    console.log('She said "hi"');        // She said "hi"
    console.log("It's mine");            // It's mine
    console.log("Line one\nLine two");   // two lines: Line one, then Line two
    

    console.log can print several values at once. It puts one space between them:

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

    주석 및 코드 스타일

    A comment 注释 is a note for people. JavaScript ignores it when the program runs.

    // 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:

    • Indent 缩进 the lines inside { } by two or four spaces, and do it the same way every time.
    • Give variables names that say what they hold: total, not t.
    • JavaScript names use camelCase 驼峰命名法: firstName, scoreTotal.
    // Work out the area of a rectangle
    const width = 4;
    const height = 3;
    console.log(width * height);   // 12
    

    Common mistakes

    • Text needs matching quotes: "Hi' is an error.
    • console.log is all lower case: Console.log and console.Log are errors.
    • Everything after // on a line is ignored, so // console.log(x) prints nothing.
    • "It's" is fine, but 'It's' ends the text at the apostrophe: an error.
  • 2 값, 변수 및 타입
    2.1

    let 및 const

    변수는 값을 저장하는 이름이 붙은 박스입니다. let 또는 const으로 생성한 후 이름을 사용하십시오:

    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
    
    • =는 대입을 의미합니다: 오른쪽을 계산한 후 왼쪽 상자에 저장합니다.
    • 기본적으로 const를 사용합니다. 값이 나중에 변경되어야 할 때만 let을 사용합니다.
    • const에 재대입하면 오류가 발생합니다: name = "Tom"은 허용되지 않습니다. const 객체나 배열도 contents를 변경할 수 있습니다.
    2.2

    숫자 & 수학

    이 예제들은 정수 및 소수용 number 타입을 사용합니다. BigInt는 별도의 정수 타입입니다. 연산자는 다음과 같습니다:

    연산자 의미 예제 결과
    + - 더하기, 빼기 7 - 2 5
    * / 곱하기, 나누기 7 / 2 3.5
    % 나머지 7 % 2 1
    ** 제곱 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
    

    Math는 유용한 함수를 포함하고 있습니다:

    console.log(Math.round(2.5));    // 3
    console.log(Math.max(4, 9, 2));  // 9
    console.log(Math.sqrt(49));      // 7
    
    • Math.random()는 0 이상 (1 미포함) 사이의 무작위 숫자를 제공합니다. Math.floor(Math.random() * 6) + 1은 1부터 6까지 주사위 굴리기 결과입니다.
    • 소수는 이_Handle로 저장되므로, 0.1 + 0.2는 0.30000000000000004을 출력합니다. 표시하기 전에 결과를 반올림하세요: (0.1 + 0.2).toFixed(2)은 "0.30"입니다.
    2.3

    타입 & 변환

    모든 값에는 유형이 있습니다. typeof는 이를 알려줍니다:

    console.log(typeof 42);         // number
    console.log(typeof "42");       // string
    console.log(typeof true);       // boolean
    console.log(typeof undefined);  // undefined
    
    • let x;로 만들고 값이 없는 변수는 undefined입니다.
    • null는 "값 없음"을 의미하며, 의도적으로 설정됩니다.

    +는 문자열과 함께 사용할 때 연결하여 더하지 않으므로, 먼저 텍스트를 숫자로 변환해야 합니다:

    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!
    
    • 숫자가 아닌 텍스트는 NaN("not a number")를 줍니다: Number("abc")은 NaN입니다.
    • -, *, /은 스스로 텍스트를 숫자로 변환할 수 있습니다 ("6" * 2은 12), 하지만 의존하지 마십시오: 의도적으로 변환하십시오.

    Common mistakes

    • =는 대입이며 비교하지 않습니다. 비교는 ===을 사용합니다 (주제 4).
    • "5" + 1는 "51"입니다. 수식 연산 전에 Number(...)로 입력값을 변환하십시오.
    • Math.round(2.5)은 3이지만, Math.round(-2.5)은 -2입니다: 반올림 시 오름 방향으로, 더 큰 수 쪽으로 반올림합니다.
  • 3 문자열
    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입니다.
    • 문자열은 불변(immutable)입니다: word[0] = "s"이 문자열을 변경하려 하면 엄격 모드에서 TypeError를 발생시킵니다. 대신 새 문자열을 생성하십시오.

    문자열을 +으로 연결할 수 있는데, 이를.Method concatenation(연결)라고 합니다:

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

    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)
    
    메서드 의미 예제 결과
    .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

    템플릿 리터럴

    템플릿 리터럴은 백틱(대부분 키보드의 1 왼쪽 키) 사이에 쓰인 문자열입니다. ${ } 내에 어떤 표현式을 넣으면 그 값이 텍스트에 삽입됩니다:

    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
    
    • 백틱은 여러 줄의 텍스트도 담을 수 있습니다.
    • 이는 많은 + 기호보다 읽기 쉽습니다: "Hi " + name + "!"과 `Hi ${name}!`을 비교해 보십시오.
    const price = 4.5;
    console.log(`Two cost $${(price * 2).toFixed(2)}`);   // Two cost $9.00
    

    Common mistakes

    • ${ }은 백틱 내부에서만 작동합니다. "Hi ${name}"에서는 입력한 대로 텍스트가 그대로 출력됩니다.
    • 메서드는 문자열을 변경하지 않습니다: 단행으로 쓴 city.trim()은 아무 일도 하지 않습니다. 결과를 변수에 저장하십시오: const clean = city.trim();.
    • slice(a, b)는 b 이전에 정지하며, 마지막 인덱스는 length - 1과 같습니다.
  • 4 조건부 결정
    4.1

    불리언 값 및 비교

    A Boolean 布尔值 is either true or false. A comparison 比较 gives a Boolean:

    Operator Meaning Example Result
    === equal (same value and same type) 5 === 5 true
    !== not equal 5 !== 3 true
    < > less than, greater than 2 > 7 false
    <= >= at most, at least 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)
    
    • Always use === and !==. The older == converts types first and gives surprising answers.

    For Boolean conditions, use the logical operators 逻辑运算符 below. With other values, && and || return one of their operands; they do not always return a Boolean:

    • && (and): true only if both sides are true.
    • || (or): true if at least one side is true.
    • ! (not): turns true into false and back.
    const age = 15;
    console.log(age >= 13 && age <= 19);   // true   (a teenager)
    console.log(age < 5 || age > 65);      // false
    console.log(!(age > 18));              // true
    
    Truth table for a and b: a && b is true only in the row where both are true; a || b is false only where both are false
    And needs both sides true; or needs at least one.
    4.2

    if / else if / else

    An if statement runs a block 代码块 of code when its condition 条件 is truthy 真值 (treated as true). With Boolean conditions, this means the value true. else if tests another condition; else catches everything left:

    const mark = 72;
    if (mark >= 80) {
      console.log("A");
    } else if (mark >= 60) {
      console.log("B");
    } else {
      console.log("C");
    }
    // prints B
    
    • JavaScript checks the conditions from the top and runs only the first true branch 分支.

    Any value can be a condition. Six values are falsy 假值, treated as false; every other value is truthy:

    Falsy values Truthy examples
    false, 0, "" (empty text), null, undefined, NaN true, 5, "0", "no", [] (an empty array)

    So if (!typed) is a short way to ask "is the text empty?":

    const typed = "";
    if (!typed) {
      console.log("Please type your name.");
    }
    // prints Please type your name.
    
    • The condition goes in round brackets; the code to run goes in curly braces { }.

    Brackets group the parts of a longer test. A year is a leap year if it divides by 4 but not by 100, or if it divides by 400:

    function isLeap(y) {
      return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
    }
    console.log(isLeap(2024), isLeap(1900), isLeap(2000));   // true false true
    

    The order of else if tests matters. Put the strictest test first:

    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

    스위치

    English

    A switch compares one value against several fixed cases. It is neater than a long else if chain when every test is "is it equal to …?":

    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 compares with ===, so case 1: does not match the string "1".
    • break ends the switch. Without it, the code falls through into the next case.
    • default runs when no case matches, like a final else.
    • Two cases with no code between them share the same code, as "Sat" and "Sun" do here.

    Common mistakes

    • if (x = 5) assigns instead of comparing, and the test is then always true. Write if (x === 5).
    • if (age > 13 && < 19) is an error: repeat the variable, age > 13 && age < 19.
    • A missing break in a switch runs the next case too.
    • The text "0" and an empty array [] are truthy. Test arr.length === 0 for an empty array.
  • 5 루프
    5.1

    for 루프

    for문 세 부분과 실행 순서

    루프는 코드 블록을 반복합니다. 반복 횟수가 이미 알려진 경우 for 루프가 가장 적합합니다. 대괄호에는 세미콜론으로 구분된 세 가지 부분이 들어갑니다:

    for (let i = 1; i <= 3; i++) {
      console.log(i);
    }
    // 1
    // 2
    // 3
    
    1. 시작: let i = 1는 루프 시작 전에 한 번만 실행됩니다.
    2. 조건: i <= 3는 매 반복 시점마다 확인되며, 조건이 거짓이 되면 루프가 종료됩니다.
    3. 진행: i++(1를 i에 더함)는 매 반복 후 실행됩니다.

    루프를 한 바퀴 도는 것을 하나의 반복(iteration)이라고 합니다. 진행 값을 변경하여 다른 방식으로 카운팅할 수 있습니다:

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

    적재 패턴(accumulator pattern)에서는 루프 전에 변수를 생성하고 매 반복마다 업데이트합니다:

    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는 루프를 즉시 종료합니다; 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
    

    Common mistakes

    • 오프바이원(off-by-one) 오류: i < 3는 0, 1, 2로 실행되며, i <= 3가 한 번 더 실행됩니다. 반복 횟수를 세십시오.
    • 합계를 루프 내부에서 시작하는 경우: let total = 0;는 루프 전에 위치해야 하며, 그렇지 않으면 매 반복마다 초기화됩니다.
    • 조건이 참으로 유지되고 종료 지점에 도달하지 않으면 while 루프는 계속 실행됩니다.
  • 6 함수
    6.1

    매개변수 및 반환값

    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)
    

    A parameter can have a default value, used when the caller leaves it out. A return near the top can also stop early when the input is wrong:

    function price(amount, taxRate = 0.1) {
      if (amount < 0) {
        return "invalid";        // stop early: nothing below runs
      }
      return (amount * (1 + taxRate)).toFixed(2);
    }
    
    console.log(price(20));      // 22.00  (taxRate is 0.1)
    console.log(price(20, 0));   // 20.00
    console.log(price(-5));      // invalid
    

    Small functions can call each other. Each does one job, so each is easy to test:

    function average(list) {
      let sum = 0;
      for (const x of list) sum += x;
      return sum / list.length;
    }
    
    function report(name, marks) {
      const avg = average(marks);
      const result = avg >= 50 ? "pass" : "fail";
      return `${name}: ${avg.toFixed(1)} (${result})`;
    }
    
    console.log(report("Mei", [62, 48, 71]));   // Mei: 60.3 (pass)
    

    Practice

    Write each function on paper first, then open the model answer, compare, and press Run.

    1. Celsius to Fahrenheit. Write toFahrenheit(c), which returns c × 9 ÷ 5 + 32. Log the answers for 0 and 100.

    Model answer
    function toFahrenheit(c) {
      return c * 9 / 5 + 32;
    }
    
    console.log(toFahrenheit(0));     // 32
    console.log(toFahrenheit(100));   // 212
    

    The formula goes after return, so each call stands for its answer.

    2. The largest of three. Write max2(a, b), then use it twice inside max3(a, b, c).

    Model answer
    function max2(a, b) {
      return a > b ? a : b;
    }
    
    function max3(a, b, c) {
      return max2(max2(a, b), c);
    }
    
    console.log(max3(4, 9, 7));    // 9
    console.log(max3(8, 2, 8));    // 8
    

    The inner call finds the larger of a and b; the outer call compares that with c. Small functions joined together are easier to test than one long one.

    3. A valid age. Write isValidAge(age), which returns true only for a whole number from 0 to 120. Test 15, -3, 12.5 and 130.

    Model answer
    function isValidAge(age) {
      return Number.isInteger(age) && age >= 0 && age <= 120;
    }
    
    for (const a of [15, -3, 12.5, 130]) {
      console.log(a, isValidAge(a));
    }
    // 15 true
    // -3 false
    // 12.5 false
    // 130 false
    

    Each && adds one rule, and all of them must hold. Test one value that breaks each rule, not only a good one.

    6.2

    화살표 함수

    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

    범위

    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.

    The same is true for any block: a let or const made inside the { } of a loop or an if ends with that block. Make the variable before the block if you need it afterwards, as total is here:

    let total = 0;
    for (let i = 1; i <= 3; i++) {
      const square = i * i;      // square exists only inside the { }
      total += square;
    }
    console.log(total);          // 14
    console.log(typeof square);  // undefined  (it ended with the loop)
    
    • Using square after the loop, as in console.log(square), stops the program with ReferenceError: square is not defined.

    A function made inside another function keeps the outer variables, even after the outer call has finished. This is a closure 闭包. Each counter below has its own count:

    function makeCounter() {
      let count = 0;
      return () => {
        count = count + 1;
        return count;
      };
    }
    
    const clicks = makeCounter();
    const visits = makeCounter();
    console.log(clicks());       // 1
    console.log(clicks());       // 2
    console.log(visits());       // 1  (a separate count)
    
    • 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.
    • An arrow function with braces and no return: (n) => { n * n } gives undefined. Write (n) => n * n or add return.
    • Calling a const arrow function before the line that makes it fails with ReferenceError; a function declaration can be called earlier in the file.
  • 7 배열(Data arrays)
    7.1

    배열 생성 및 수정

    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)
    

    To visit every element, use a for...of loop. It gives you each value in turn, so you need no index:

    const marks = [12, 7, 15];
    let total = 0;
    for (const m of marks) {
      total += m;
    }
    console.log(total);            // 34
    

    An array variable holds a reference 引用 to the array, not a copy. const b = a gives the same array a second name, so a change through b also shows in a. Use [...a] when you want a real copy:

    const a = [1, 2, 3];
    const b = a;                   // same array, two names
    b.push(4);
    console.log(a);                // [1,2,3,4]
    
    const c = [...a];              // a new array with the same values
    c.push(5);
    console.log(a.length, c.length);   // 4 5
    

    Two more methods you will use often: slice copies part of an array, and join turns it into one string.

    const words = ["red", "green", "blue"];
    console.log(words.slice(0, 2));     // ["red","green"]  (stops before index 2)
    console.log(words.join(" - "));     // red - green - blue
    
    7.2

    map, filter 및 reduce

    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. For [3, 8, 5].reduce((sum, n) => sum + n, 0):

    Element n sum before sum + n (the new sum)
    3 0 3
    8 3 11
    5 11 16

    The result is the last sum, 16.

    You can chain 链式调用 these methods: each one works on the array that the one before it returned. Read the chain from left to right:

    const scores = [55, 82, 47, 91, 68];
    const passed = scores
      .filter((s) => s >= 50)    // [55,82,91,68]
      .map((s) => s + 5);        // add 5 bonus points
    console.log(passed);         // [60,87,96,73]
    

    Practice

    Each task has one line of work: choose map, filter or reduce. Write it on paper first, then open the model answer, compare, and press Run.

    1. Prices with tax. const prices = [10, 25, 4]; Make a new array with 20% tax added to each price.

    Model answer
    const prices = [10, 25, 4];
    const withTax = prices.map((p) => p * 1.2);
    console.log(withTax);        // [12,30,4.8]
    

    map: one new value for each old one, so the new array has the same length.

    2. Names that start with A. const names = ["Ana", "Ben", "Aisha", "Carl"]; Keep only the names that start with "A".

    Model answer
    const names = ["Ana", "Ben", "Aisha", "Carl"];
    const aNames = names.filter((n) => n.startsWith("A"));
    console.log(aNames);         // ["Ana","Aisha"]
    

    filter: the function answers yes or no for each item, and only the yes items are kept.

    3. The longest word's length. const words = ["sun", "planet", "moon"]; Find the length of the longest word.

    Model answer
    const words = ["sun", "planet", "moon"];
    const longest = words.reduce((best, w) => Math.max(best, w.length), 0);
    console.log(longest);        // 6
    

    reduce: many items become one value. best starts at 0 and keeps the larger of itself and each word's length. words.map((w) => w.length) then Math.max(...) also works.

    7.3

    검색 및 정렬

    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.

    To sort objects, compare one of their properties. Subtract numbers; for text, use localeCompare, which returns a negative or positive number in the same way:

    const people = [
      { name: "Ann", age: 15 },
      { name: "Ben", age: 12 },
      { name: "Cai", age: 14 },
    ];
    const byAge = [...people].sort((x, y) => x.age - y.age);
    console.log(byAge.map((p) => p.name));     // ["Ben","Cai","Ann"]
    
    const byName = [...people].sort((x, y) => x.name.localeCompare(y.name));
    console.log(byName[0].name);               // Ann
    

    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.
    • const b = a does not copy an array. Change b and a changes too; copy with [...a].
    • reduce without a start value uses the first element instead. Give the start value (0 for a total) every time.
  • 8 오브젝트
    8.1

    객체 및 속성

    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"}
    

    Two names, one object. const b = a; does not copy an object: both names point to the same object, so a change through one name shows through the other. Make a real copy with { ...a }:

    const a = { name: "Mei", mark: 88 };
    const b = a;              // same object, second name
    const c = { ...a };       // a new object with the same properties
    b.mark = 50;
    console.log(a.mark);      // 50  (changed through b!)
    console.log(c.mark);      // 88  (the copy is separate)
    console.log(a === b);     // true   (same object)
    console.log(a === c);     // false  (different objects, even with equal contents)
    

    A property can hold a function. It is then a method, and this inside it means the object it was called on:

    const account = {
      owner: "Sam",
      balance: 40,
      pay(amount) {
        if (amount > this.balance) {
          return "not enough money";
        }
        this.balance -= amount;
        return `paid ${amount}, ${this.balance} left`;
      },
    };
    console.log(account.pay(15));   // paid 15, 25 left
    console.log(account.pay(30));   // not enough money
    

    Classes: many objects of the same shape

    When you need many objects with the same properties and methods, write a class 类 once. The constructor 构造函数 runs when you write new, and sets each new object's properties through this:

    class Account {
      constructor(owner, balance) {
        this.owner = owner;
        this.balance = balance;
      }
      pay(amount) {
        if (amount > this.balance) {
          return "not enough money";
        }
        this.balance -= amount;
        return `${this.owner} paid ${amount}, ${this.balance} left`;
      }
    }
    
    const sam = new Account("Sam", 40);
    const mei = new Account("Mei", 100);
    console.log(sam.pay(15));   // Sam paid 15, 25 left
    console.log(mei.pay(15));   // Mei paid 15, 85 left
    console.log(sam.balance);   // 25: each object keeps its own balance
    
    • Methods inside a class have no function word and no commas between them.
    • Forgetting new stops the program: Account("Sam", 40) gives a TypeError.
    8.2

    객체 배열

    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

    객체 순환하기

    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(...).
    • === on two objects asks "the same object?", not "the same contents?": { x: 1 } === { x: 1 } is false.
    • { ...a } copies one level only: an array or object inside a is still shared.
  • 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("…")은 message이 사용자 텍스트인 오류를 생성합니다.
    • 실제로 실패할 수 있는 코드(예: 데이터 읽기)에만 try을 사용하십시오. 사용자 코드의 실수를 숨기기 위해 사용하지 마십시오.

    Common mistakes

    • 메시지 건너뛰기. 첫 줄은 오류 유형과 원인을 명시하므로, 거기를 먼저 확인하십시오.
    • catch이 아무것도 하지 않으면(catch (e) {}), 문제가 가려집니다: 적어도 e.message을 출력하십시오.
    • throw "text"은 작동하지만, throw new Error("text")도 오류가 발생한 위치를 기록합니다.

로그인 또는 계정 만들기

IGCSE, A-Level & AP