Перейти к содержанию
Предметы
  • 1 Начало работы
    1.1

    Ваша первая программа

    Программа — это список инструкций для компьютера. В JavaScript каждая инструкция является оператором (statement), и компьютер выполняет операторы сверху вниз.

    console.log(...) выводит значение в консоль, текстовой области под кодом:

    console.log("Hello, world!");
    console.log(7 * 6);   // 42
    
    • Текст помещается в кавычки: "Hello" или 'Hello'. Числа — нет.
    • Завершайте каждый оператор точкой с запятой ;. 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

    Комментарии и стиль кода

    Комментарий — это заметка для людей. 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");
    

    Хороший стиль делает код легким для чтения:

    • Отступайте строки внутри { } на два или четыре пробела и делайте это одинаково всегда.
    • Называйте переменные так, чтобы они отражали хранящееся значение: 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 Значения, переменные и типы
    2.1

    let и 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

    Числа и математика

    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

    Типы и преобразование

    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 Строки
    3.1

    Символы и длина

    A string 字符串 is text inside quotes. With simple letters, each character 字符 has one position, its index 索引; the first index is 0. JavaScript counts UTF-16 code units: an emoji may take two positions.

    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
    
    • The last index is length - 1. word[6] is undefined, not an error.
    • Strings are immutable 不可变: word[0] = "s" cannot change the string and throws a TypeError in strict mode. Build a new string instead.

    Join strings with +, which is called concatenation 拼接:

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

    Методы строки

    A method 方法 is a function that belongs to a value. Call it with a dot. A string method gives back a new value and leaves the original alone.

    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 Meaning Example Result
    .toUpperCase() / .toLowerCase() change case "Hi".toLowerCase() "hi"
    .trim() remove spaces at both ends " hi ".trim() "hi"
    .includes(t) does it contain t? "cat".includes("a") true
    .indexOf(t) first position of t, or -1 "cat".indexOf("t") 2
    .slice(a, b) characters from a up to (not including) b "Script".slice(0, 3) "Scr"
    .split(sep) break into an array "a,b,c".split(",") ["a","b","c"]
    .replace(a, b) swap the first a for 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"]
    
    The string mei@school.org in numbered boxes from 0 to 13, with the @ at index 3; slice 0 to at covers mei and slice at plus 1 covers school.org
    indexOf finds the @ at 3; the two slices take the parts either side of it.
    3.3

    Шаблонные строки

    A template literal 模板字面量 is a string written between backticks (on most keyboards, the key left of 1). Put any expression 表达式 inside ${ } and its value is placed into the text:

    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
    
    • Backticks can also hold several lines of text.
    • This is easier to read than many + signs: compare "Hi " + name + "!" with `Hi ${name}!`.
    const price = 4.5;
    console.log(`Two cost $${(price * 2).toFixed(2)}`);   // Two cost $9.00
    

    Common mistakes

    • ${ } only works inside backticks. In "Hi ${name}" the text is printed exactly as typed.
    • Methods do not change the string: city.trim() on its own line does nothing. Store the result: const clean = city.trim();.
    • slice(a, b) stops before b, just like the last index is length - 1.
  • 4 Условия
    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)
    
    • Всегда используйте === и !==. Устаревшие == сначала преобразуют типы и могут дать неожиданный результат.

    Для логических условий используйте нижеперечисленные операторы. Для других значений && и || возвращают один из своих операндов; они не всегда возвращают логическое значение:

    • && (и): истинно, только если обе части истинны.
    • || (или): истинно, если хотя бы одна часть истинна.
    • ! (не): превращает 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 выполняет блок кода, если условие истинно (трактуется как истина). С логическими значениями это означает значение 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 проверяет условия сверху и выполняет только первый истинный блок.
    • Условие пишется в круглых скобках; код для выполнения — в фигурных скобках { }.

    Поэтому порядок имеет значение. Сначала ставьте наиболее строгую проверку:

    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

    выключатель

    Конструкция 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: не совпадает со строкой "1".
    • break завершает ветвление switch. Без него код переходит к следующему варианту.
    • default выполняется, когда ни один случай не совпадает, подобно конечному else.
    • Два варианта без кода между собой используют один и тот же код, как в случае со "Sat" и "Sun" здесь.

    Распространенные ошибки

    • В конструкции if (x = 5) используется присваивание вместо сравнения, поэтому проверка всегда возвращает истину. Пишите if (x === 5).
    • Повторение переменной в конструкции if (age > 13 && < 19) является ошибкой: используйте age > 13 && age < 19.
    • Отсутствие ключевого слова break в конструкции switch приводит к выполнению следующего варианта.
  • 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) выполняется после каждого прохода.

    Каждый проход через цикл называется одной итерацией. Измените шаг, чтобы счётчик изменялся иначе:

    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
    
    • Условие проверяется перед каждым проходом, поэтому тело может не выполниться ни разу.
    • Если условие остаётся истинным и не достигается ключевое слово 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
    

    Распространенные ошибки

    • Ошибка «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)
    
    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.
    • 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 Массивы
    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)
    
    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

    Поиск и сортировка

    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 Объекты
    8.1

    Объекты и свойства

    Объект группирует связанные значения под именами. Каждая пара «имя-значение» является свойством. Имя называется ключом:

    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)
    
    • Прочитайте свойство с помощью точки (pupil.age) или скобок (pupil["age"]). Используйте скобки, когда ключ находится в переменной: pupil[field].
    • Несуществующий ключ возвращает undefined.

    Измените свойство или добавьте новое, присвоив ему значение:

    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

    Массивы объектов

    Список записей — это массив объектов. Объедините его с методами массива из темы 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
    

    Чтобы просуммировать свойство, используйте reduce или цикл:

    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 возвращает массив ключей, а Object.entries — пары [key, value], так что можно пройтись по ним циклом:

    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
    

    Объект подходит для подсчета: используйте каждый подсчитываемый объект в качестве ключа.

    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}
    

    Распространенные ошибки

    • pupil.field ищет ключ с именем field. Когда ключ находится в переменной, запишите pupil[field].
    • Запятая ставится между свойствами, а не точка с запятой: { name: "Mei", age: 17 }.
    • for...of не может перебирать объект напрямую. Перебирайте Object.keys(...) или Object.entries(...).
  • 9 Ошибки
    9.1

    Чтение сообщений об ошибках

    When JavaScript cannot carry on, it stops and shows an error 错误. The first word names the kind of error; the rest says what went wrong and where. Read it, then look at the line it names.

    SyntaxError: missing ) after argument list
    ReferenceError: totl is not defined
    TypeError: Cannot read properties of undefined (reading 'length')
    
    The TypeError message split into two parts: the error name, then what went wrong, that .length was used on undefined
    First the kind of error, then what went wrong.
    Error What it means A typical cause
    SyntaxError the code is not written correctly, so nothing runs a missing bracket or quote
    ReferenceError a name that does not exist a spelling mistake 拼写错误: totl for total
    TypeError the value is the wrong type for what you did using .length on undefined

    The exact wording can differ between browsers, but the name of the error is the same. This program catches each error so that it can print its name:

    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
    }
    

    Some mistakes give no error at all, just a wrong answer: a logic error 逻辑错误. To find one, print the values along the way with console.log, and check them by hand.

    9.2

    try, catch и throw

    Code that might fail goes in a try block. If an error happens there, JavaScript jumps to catch instead of stopping, and e holds the error:

    try {
      JSON.parse("{not valid}");
      console.log("parsed");         // skipped
    } catch (e) {
      console.log("Could not read the data");
    }
    console.log("The program carries on");
    
    Flow from a try block: with no error the rest of try runs; with an error the rest is skipped and catch runs; both paths reach the line after
    Either way, the program reaches the line after catch.

    Your own code can raise an error with throw. This lets a function refuse bad input 输入 clearly, instead of returning a wrong answer:

    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("…") makes an error whose message is your text.
    • Only use try around code that can really fail, such as reading data. Do not use it to hide mistakes in your own code.

    Common mistakes

    • Skipping the message. Its first line names the kind of error and what went wrong; start there.
    • A catch that does nothing (catch (e) {}) hides the problem: at least print e.message.
    • throw "text" works, but throw new Error("text") also records where the error happened.

Войти или создать аккаунт

IGCSE, A-Level & AP