JavaScript 备忘清单

包含最重要概念、函数、方法等的 JavaScript 备忘单。 初学者的完整快速参考。

入门

介绍

JavaScript 是一种轻量级的解释型编程语言。

打印调试

  1. // => Hello world!
  2. console.log('Hello world!');
  3. // => Hello QuickReference
  4. console.warn('hello %s', 'QuickReference');
  5. // 将错误消息打印到 stderr
  6. console.error(new Error('Oops!'));

断点调试

  1. function potentiallyBuggyCode() {
  2. debugger;
  3. // 做可能有问题的东西来检查,逐步通过等。
  4. }

debugger 语句调用任何可用的调试功能。

数字

  1. let amount = 6;
  2. let price = 4.99;
  3. let home = 1e2;
  4. let m = 0644; // 八进制数字 420

let 关键字

  1. let count;
  2. console.log(count); // => undefined
  3. count = 10;
  4. console.log(count); // => 10

const 关键字

  1. const numberOfColumns = 4;
  2. // TypeError: Assignment to constant...
  3. numberOfColumns = 8;

变量

  1. let x = null;
  2. let name = "Tammy";
  3. const found = false;
  4. // => Tammy, false, null
  5. console.log(name, found, x);
  6. var a;
  7. console.log(a); // => undefined

字符串

  1. let single = 'Wheres my bandit hat?';
  2. let double = "Wheres my bandit hat?";
  3. // => 21
  4. console.log(single.length);

算术运算符

  1. 5 + 5 = 10 // 加法 Addition
  2. 10 - 5 = 5 // 加法 Subtraction
  3. 5 * 10 = 50 // 乘法 Multiplication
  4. 10 / 5 = 2 // 除法 Division
  5. 10 % 5 = 0 // 取模 Modulo

注释

  1. // 此行将表示注释
  2. /*
  3. 多行配置
  4. 部署前必须更改
  5. 以下配置。
  6. */

赋值运算符

  1. let number = 100;
  2. // 两个语句都会加 10
  3. number = number + 10;
  4. number += 10;
  5. console.log(number);
  6. // => 120

字符串插值

  1. let age = 7;
  2. // 字符串拼接
  3. 'Tommy is ' + age + ' years old.';
  4. // 字符串插值
  5. `Tommy is ${age} years old.`;

字符串

  1. var abc = "abcdefghijklmnopqrstuvwxyz";
  2. var esc = 'I don\'t \n know'; // \n 换行
  3. var len = abc.length; // 字符串长度
  4. abc.indexOf("lmno"); // 查找子字符串,如果不包含则 -1
  5. abc.lastIndexOf("lmno"); // 最后一次出现
  6. abc.slice(3, 6); // 去掉“def”,负值从后面计算
  7. abc.replace("abc","123"); // 查找和替换,接受正则表达式
  8. abc.toUpperCase(); // 转换为大写
  9. abc.toLowerCase(); // 转换为小写
  10. abc.concat(" ", str2); // abc + " " + str2
  11. abc.charAt(2); // 索引处的字符:“c”
  12. abc[2]; // 不安全,abc[2] = "C" 不起作用
  13. // 索引处的字符代码:“c”-> 99
  14. abc.charCodeAt(2);
  15. // 用逗号分割字符串给出一个数组
  16. abc.split(",");
  17. // 分割字符
  18. abc.split("");
  19. // 数字转为十六进制 (16)、八进制 (8) 或二进制 (2)
  20. 128.toString(16);

数字

  1. var pi = 3.141;
  2. pi.toFixed(0); // 返回 3
  3. pi.toFixed(2); // 返回 3.14 - 使用金钱
  4. pi.toPrecision(2) // 返回 3.1
  5. pi.valueOf(); // 返回号码
  6. Number(true); // 转换为数字
  7. // 自 1970 年以来的毫秒数
  8. Number(new Date())
  9. // 返回第一个数字:3
  10. parseInt("3 months");
  11. // 返回 3.5
  12. parseFloat("3.5 days");
  13. // 最大可能的 JS 数
  14. Number.MAX_VALUE
  15. // 最小可能的 JS 编号
  16. Number.MIN_VALUE
  17. // -无穷
  18. Number.NEGATIVE_INFINITY
  19. // 无穷
  20. Number.POSITIVE_INFINITY

Math

  1. const pi = Math.PI; // 3.141592653589793
  2. Math.round(4.4); // = 4 - 数字四舍五入
  3. Math.round(4.5); // = 5
  4. Math.pow(2,8); // = 256 - 2 的 8 次方
  5. Math.sqrt(49); // = 7 - 平方根
  6. Math.abs(-3.14); // = 3.14 - 绝对,正值
  7. Math.ceil(3.14); // = 4 - 返回 >= 最小整数
  8. // = 3 - 返回 <= 最大整数
  9. Math.floor(3.99);
  10. // = 0 - 正弦
  11. Math.sin(0);
  12. // OTHERS: tan,atan,asin,acos,余弦值
  13. Math.cos(Math.PI);
  14. // = -2 - 最低值
  15. Math.min(0, 3, -2, 2);
  16. // = 3 - 最高值
  17. Math.max(0, 3, -2, 2);
  18. // = 0 自然对数
  19. Math.log(1);
  20. // = 2.7182pow(E,x) 自然对数的底数
  21. Math.exp(1);
  22. // 0 到 1 之间的随机数
  23. Math.random();
  24. // 随机整数,从 1
  25. Math.floor(Math.random() * 5) + 1;

全局函数

  1. // 像脚本代码一样执行字符串
  2. eval();
  3. // 从数字返回字符串
  4. String(23);
  5. // 从数字返回字符串
  6. (23).toString();
  7. // 从字符串返回数字
  8. Number("23");
  9. // 解码 URI。 结果:“我的 page.asp”
  10. decodeURI(enc);
  11. // 编码 URI。 结果:“my%page.asp”
  12. encodeURI(uri);
  13. // 解码 URI 组件
  14. decodeURIComponent(enc);
  15. // 对 URI 组件进行编码
  16. encodeURIComponent(uri);
  17. // 是一个有限的合法数
  18. isFinite();
  19. // 是一个非法数字
  20. isNaN();
  21. // 返回字符串的浮点数
  22. parseFloat();
  23. // 解析一个字符串并返回一个整数
  24. parseInt();

JavaScript 条件

操作符

  1. true || false; // true
  2. 10 > 5 || 10 > 20; // true
  3. false || false; // false
  4. 10 > 100 || 10 > 20; // false

逻辑运算符 &&

  1. true && true; // true
  2. 1 > 2 && 2 > 1; // false
  3. true && false; // false
  4. 4 === 4 && 3 > 1; // true

比较运算符

  1. 1 > 3 // false
  2. 3 > 1 // true
  3. 250 >= 250 // true
  4. 1 === 1 // true
  5. 1 === 2 // false
  6. 1 === '1' // false

逻辑运算符 !

  1. let lateToWork = true;
  2. let oppositeValue = !lateToWork;
  3. // => false
  4. console.log(oppositeValue);

空值合并运算符 ??

  1. null ?? 'I win'; // 'I win'
  2. undefined ?? 'Me too'; // 'Me too'
  3. false ?? 'I lose' // false
  4. 0 ?? 'I lose again' // 0
  5. '' ?? 'Damn it' // ''

if Statement (if 语句)

  1. const isMailSent = true;
  2. if (isMailSent) {
  3. console.log('Mail sent to recipient');
  4. }

Ternary Operator (三元运算符)

  1. var age = 1;
  2. // => true
  3. var status = (age >= 18) ? true : false;

else if

  1. const size = 10;
  2. if (size > 20) {
  3. console.log('Medium');
  4. } else if (size > 4) {
  5. console.log('Small');
  6. } else {
  7. console.log('Tiny');
  8. }
  9. // Print: Small

== vs ===

  1. 0 == false // true
  2. 0 === false // false, 不同类型
  3. 1 == "1" // true, 自动类型转换
  4. 1 === "1" // false, 不同类型
  5. null == undefined // true
  6. null === undefined // false
  7. '0' == false // true
  8. '0' === false // false

== 只检查值,=== 检查值和类型。

switch 语句

  1. const food = 'salad';
  2. switch (food) {
  3. case 'oyster': console.log('海的味道');
  4. break;
  5. case 'pizza': console.log('美味的馅饼');
  6. break;
  7. default:
  8. console.log('请您用餐');
  9. }

switch 多 case - 单一操作

  1. const food = 'salad';
  2. switch (food) {
  3. case 'oyster':
  4. case 'pizza':
  5. console.log('美味的馅饼');
  6. break;
  7. default:
  8. console.log('请您用餐');
  9. }

JavaScript Functions 函数

函数

  1. // 定义函数:
  2. function sum(num1, num2) {
  3. return num1 + num2;
  4. }
  5. // 调用函数:
  6. sum(3, 6); // 9

匿名函数

  1. // 命名函数
  2. function rocketToMars() {
  3. return 'BOOM!';
  4. }
  5. // 匿名函数
  6. const rocketToMars = function() {
  7. return 'BOOM!';
  8. }

箭头函数 (ES6)

有两个参数

  1. const sum = (param1, param2) => {
  2. return param1 + param2;
  3. };
  4. console.log(sum(2,5)); // => 7

没有参数

  1. const printHello = () => {
  2. console.log('hello');
  3. };
  4. printHello(); // => hello

只有一个参数

  1. const checkWeight = weight => {
  2. console.log(`Weight : ${weight}`);
  3. };
  4. checkWeight(25); // => Weight : 25

简洁箭头函数

  1. const multiply = (a, b) => a * b;
  2. // => 60
  3. console.log(multiply(2, 30));

从 ES2015 开始提供箭头函数

返回关键字

  1. // 有 return
  2. function sum(num1, num2) {
  3. return num1 + num2;
  4. }
  5. // 该函数不输出总和
  6. function sum(num1, num2) {
  7. num1 + num2;
  8. }

调用函数

  1. // 定义函数
  2. function sum(num1, num2) {
  3. return num1 + num2;
  4. }
  5. // 调用函数
  6. sum(2, 4); // 6

函数表达式

  1. const dog = function() {
  2. return 'Woof!';
  3. }

函数参数

  1. // 参数是 name
  2. function sayHello(name) {
  3. return `Hello, ${name}!`;
  4. }

函数声明

  1. function add(num1, num2) {
  2. return num1 + num2;
  3. }

JavaScript 范围

范围

  1. function myFunction() {
  2. var pizzaName = "Margarita";
  3. // 这里的代码可以使用 PizzaName
  4. }
  5. // ❌ PizzaName 不能在这里使用

{ } 块内声明的变量

  1. {
  2. let x = 2;
  3. }
  4. // ❌ x 不能在这里使用
  5. {
  6. var x = 2;
  7. }
  8. // ✅ x 能在这里使用
  1. var x = 2; // Global scope
  2. let x = 2; // Global scope
  3. const x = 2; // Global scope

ES6 引入了两个重要的新 JavaScript 关键字:let 和 const。这两个关键字在 JavaScript 中提供了块作用域。

块作用域变量

  1. const isLoggedIn = true;
  2. if (isLoggedIn == true) {
  3. const statusMessage = 'Logged in.';
  4. }
  5. // Uncaught ReferenceError...
  6. // 未捕获的引用错误...
  7. console.log(statusMessage);

全局变量

  1. // 全局声明的变量
  2. const color = 'blue';
  3. function printColor() {
  4. console.log(color);
  5. }
  6. printColor(); // => blue

let vs var

  1. for (let i = 0; i < 3; i++) {
  2. // 这是“let”的最大范围
  3. // i 可以访问 ✔️
  4. }
  5. // i 不能访问 ❌

  1. for (var i = 0; i < 3; i++) {
  2. // i 可以访问 ✔️
  3. }
  4. // i 可以访问 ✔️

var 的范围是最近的函数块,而 let 的范围是最近的封闭块。

带闭包的循环

  1. // 打印三次,不是我们的意思。
  2. for (var i = 0; i < 3; i++) {
  3. setTimeout(_ => console.log(i), 10);
  4. }

  1. // 按预期打印 0、1 和 2。
  2. for (let j = 0; j < 3; j++) {
  3. setTimeout(_ => console.log(j), 10);
  4. }

变量使用 let 有自己的副本,变量有使用 var 的共享副本。

JavaScript Arrays

方法

:- :-
Array.from() 类似数组对象创建一个新的 #
Array.isArray() 值是否是一个 Array #
Array.of() 创建一个新数组示例 #
.at() 返回值索引对应的元素 #
.concat() 合并两个或多个数组 #
.copyWithin() 浅复制替换某个位置 #
.entries() 新的 Array Iterator 对象 #
.every() 是否能通过回调函数的测试 #
.fill() 固定值填充一个数组中 #
.filter() 返回过滤后的数组 #
.find() 第一个元素的值 #
.findIndex() 第一个元素的索引 #
.findLast() 最后一个元素的值 #
.findLastIndex() 最后一个元素的索引 #
.flat() 扁平化嵌套数组 #
.flatMap() 与 flat 相同 #
.forEach() 升序循环执行 #
.includes() 是否包含一个指定的值 #
.indexOf() 找到给定元素的第一个索引 #
.join() 数组链接成一个字符串 #
.keys() 每个索引键 #
.lastIndexOf() 给定元素的最后一个索引 #
.map() 循环返回一个新数组 #
.pop() 删除最后一个元素 #
.push() 元素添加到数组的末尾 #
.reduce() 循环函数传递当前和上一个值 #
.reduceRight() 类似 reduce 从右往左循环 #
.reverse() 数组元素的位置颠倒 #
.shift() 删除第一个元素 #
.slice() 提取元素 #
.some() 至少有一个通过测试函数 #
.sort() 元素进行排序 #
.splice() 删除替换添加元素 #
.toLocaleString() 字符串表示数组中的元素 #
.toString() 返回字符串 #
.unshift() 元素添加到数组的开头 #
.values() 返回新的 ArrayIterator 对象 #

数组

  1. const fruits = ["apple", "dew", "banana"];
  2. // 不同的数据类型
  3. const data = [1, 'chicken', false];

属性 .length

  1. const numbers = [1, 2, 3, 4];
  2. numbers.length // 4

索引

  1. // 访问数组元素
  2. const myArray = [100, 200, 300];
  3. console.log(myArray[0]); // 100
  4. console.log(myArray[1]); // 200

可变图表

添加 删除 开始 结束
push
pop
unshift
shift

方法 .push()

  1. // 添加单个元素:
  2. const cart = ['apple', 'orange'];
  3. cart.push('pear');
  4. // 添加多个元素:
  5. const numbers = [1, 2];
  6. numbers.push(3, 4, 5);

将项目添加到末尾并返回新的数组长度。

方法 .pop()

  1. const fruits = ["apple", "dew", "banana"];
  2. const fruit = fruits.pop(); // 'banana'
  3. console.log(fruits); // ["apple", "dew"]

末尾删除一个项目并返回已删除的项目。

方法 .shift()

  1. const array1 = [1, 2, 3];
  2. const firstElement = array1.shift();
  3. console.log(array1); // 输出: Array [2, 3]
  4. console.log(firstElement); // 输出: 1

从头删除一个项目并返回已删除的项目。

方法 .some()

  1. const array = [1, 2, 3, 4, 5];
  2. // 检查元素是否为偶数
  3. const even = (element) => element % 2 === 0;
  4. console.log(array.some(even));
  5. // 预期输出: true

方法 .concat()

  1. const numbers = [3, 2, 1]
  2. const newFirstNumber = 4
  3. // => [ 4, 3, 2, 1 ]
  4. [newFirstNumber].concat(numbers)
  5. // => [ 3, 2, 1, 4 ]
  6. numbers.concat(newFirstNumber)

如果你想避免改变你的原始数组,你可以使用 concat。

方法 .splice()

  1. const months = ['Jan', 'March'];
  2. months.splice(1, 0, 'Feb');
  3. // 在索引 1 处插入
  4. console.log(months);
  5. // 预期输出: Array ["Jan", "Feb", "March"]
  6. months.splice(2, 1, 'May');
  7. // 替换索引 2 处的 1 个元素
  8. console.log(months);
  9. // 预期输出: Array ["Jan", "Feb", "May"]

方法 .unshift()

  1. let cats = ['Bob'];
  2. // => ['Willy', 'Bob']
  3. cats.unshift('Willy');
  4. // => ['Puff', 'George', 'Willy', 'Bob']
  5. cats.unshift('Puff', 'George');

将项目添加到开头并返回新的数组长度。

方法 .filter()

  1. const words = ['js', 'java', 'golang'];
  2. const result = words.filter(word => {
  3. return word.length > 3
  4. });
  5. console.log(result);
  6. // 预期输出: Array ["java", "golang"]

JavaScript 循环

While 循环

  1. while (condition) {
  2. // 要执行的代码块
  3. }
  4. let i = 0;
  5. while (i < 5) {
  6. console.log(i);
  7. i++;
  8. }

反向循环

  1. const fruits = ["apple", "dew", "berry"];
  2. for (let i = fruits.length - 1; i >= 0; i--) {
  3. console.log(`${i}. ${fruits[i]}`);
  4. }
  5. // => 2. berry
  6. // => 1. dew
  7. // => 0. apple

Do…While 语句

  1. x = 0
  2. i = 0
  3. do {
  4. x = x + i;
  5. console.log(x)
  6. i++;
  7. } while (i < 5);
  8. // => 0 1 3 6 10

For 循环

  1. for (let i = 0; i < 4; i += 1) {
  2. console.log(i);
  3. };
  4. // => 0, 1, 2, 3

遍历数组

  1. for (let i = 0; i < array.length; i++){
  2. console.log(array[i]);
  3. }
  4. // => 数组中的每一项

Break

  1. for (let i = 0; i < 99; i += 1) {
  2. if (i > 5) break;
  3. console.log(i)
  4. }
  5. // => 0 1 2 3 4 5

Continue

  1. for (i = 0; i < 10; i++) {
  2. if (i === 3) {
  3. continue;
  4. }
  5. text += "The number is " + i + "<br>";
  6. }

嵌套循环

  1. for (let i = 0; i < 2; i += 1) {
  2. for (let j = 0; j < 3; j += 1) {
  3. console.log(`${i}-${j}`);
  4. }
  5. }

for…in 循环

  1. const fruits = ["apple", "orange", "banana"];
  2. for (let index in fruits) {
  3. console.log(index);
  4. }
  5. // => 0
  6. // => 1
  7. // => 2

label 语句

  1. var num = 0;
  2. outPoint:
  3. for(var i = 0; i < 10; i++) {
  4. for(var j = 0; j < 10; j++) {
  5. if(i == 5 && j == 5) {
  6. continue outPoint;
  7. }
  8. num++;
  9. }
  10. }
  11. alert(num); // 95

alert(num) 的值可以看出,continue outPoint; 语句的作用是跳出当前循环,并跳转到 outPoint(标签)下的 for 循环继续执行。

for…of 循环

  1. const fruits = ["apple", "orange", "banana"];
  2. for (let fruit of fruits) {
  3. console.log(fruit);
  4. }
  5. // => apple
  6. // => orange
  7. // => banana

for await…of

  1. async function* asyncGenerator() {
  2. var i = 0;
  3. while (i < 3) {
  4. yield i++;
  5. }
  6. }
  7. (async function() {
  8. for await (num of asyncGenerator()) {
  9. console.log(num);
  10. }
  11. })();
  12. // 0
  13. // 1
  14. // 2

可选的 for 表达式

  1. var i = 0;
  2. for (;;) {
  3. if (i > 3) break;
  4. console.log(i);
  5. i++;
  6. }

JavaScript 迭代器(Iterators)

分配给变量的函数

  1. let plusFive = (number) => {
  2. return number + 5;
  3. };
  4. // f 被赋值为 plusFive
  5. let f = plusFive;
  6. plusFive(3); // 8
  7. // 由于 f 具有函数值,因此可以调用它。
  8. f(9); // 14

回调函数

  1. const isEven = (n) => {
  2. return n % 2 == 0;
  3. }
  4. let printMsg = (evenFunc, num) => {
  5. const isNumEven = evenFunc(num);
  6. console.log(`${num} is an even number: ${isNumEven}.`)
  7. }
  8. // Pass in isEven as the callback function
  9. printMsg(isEven, 4);
  10. // => The number 4 is an even number: True.

数组方法 .reduce()

  1. const numbers = [1, 2, 3, 4];
  2. const sum = numbers.reduce((accumulator, curVal) => {
  3. return accumulator + curVal;
  4. });
  5. console.log(sum); // 10

数组方法 .map()

  1. const members = ["Taylor", "Donald", "Don", "Natasha", "Bobby"];
  2. const announcements = members.map((member) => {
  3. return member + " joined the contest.";
  4. });
  5. console.log(announcements);

数组方法 .forEach()

  1. const numbers = [28, 77, 45, 99, 27];
  2. numbers.forEach(number => {
  3. console.log(number);
  4. });

数组方法 .filter()

  1. const randomNumbers = [4, 11, 42, 14, 39];
  2. const filteredArray = randomNumbers.filter(n => {
  3. return n > 5;
  4. });

JavaScript 对象(Objects)

访问属性

  1. const apple = {
  2. color: 'Green',
  3. price: { bulk: '$3/kg', smallQty: '$4/kg' }
  4. };
  5. console.log(apple.color); // => Green
  6. console.log(apple.price.bulk); // => $3/kg

命名属性

  1. // 无效键名示例
  2. const trainSchedule = {
  3. // 由于单词之间的空格而无效。
  4. platform num: 10,
  5. // 表达式不能是键。
  6. 40 - 10 + 2: 30,
  7. // 除非用引号括起来,否则 + 号无效。
  8. +compartment: 'C'
  9. }

不存在的属性

  1. const classElection = {
  2. date: 'January 12'
  3. };
  4. console.log(classElection.place); // undefined

可变的

  1. const student = {
  2. name: 'Sheldon',
  3. score: 100,
  4. grade: 'A',
  5. }
  6. console.log(student)
  7. // { name: 'Sheldon', score: 100, grade: 'A' }
  8. delete student.score
  9. student.grade = 'F'
  10. console.log(student)
  11. // { name: 'Sheldon', grade: 'F' }
  12. student = {}
  13. // TypeError: TypeError:分配给常量变量。

赋值简写语法

  1. const person = {
  2. name: 'Tom',
  3. age: '22',
  4. };
  5. const {name, age} = person;
  6. console.log(name); // 'Tom'
  7. console.log(age); // '22'

删除运算符

  1. const person = {
  2. firstName: "Matilda",
  3. hobby: "knitting",
  4. goal: "learning JavaScript"
  5. };
  6. delete person.hobby; // 或 delete person['hobby'];
  7. console.log(person);
  8. /*
  9. {
  10. firstName: "Matilda"
  11. goal: "learning JavaScript"
  12. } */

对象作为参数

  1. const origNum = 8;
  2. const origObj = {color: 'blue'};
  3. const changeItUp = (num, obj) => {
  4. num = 7;
  5. obj.color = 'red';
  6. };
  7. changeItUp(origNum, origObj);
  8. // 将输出 8,因为整数是按值传递的。
  9. console.log(origNum);
  10. // 由于传递了对象,将输出“red”
  11. // 通过引用,因此是可变的。
  12. console.log(origObj.color);

工厂函数

  1. // 一个接受 'name','age' 和 'breed' 的工厂函数,
  2. // 参数返回一个自定义的 dog 对象。
  3. const dogFactory = (name, age, breed) => {
  4. return {
  5. name: name,
  6. age: age,
  7. breed: breed,
  8. bark() {
  9. console.log('Woof!');
  10. }
  11. };
  12. };

速记对象创建

  1. const activity = 'Surfing';
  2. const beach = { activity };
  3. console.log(beach); // { activity: 'Surfing' }

this 关键字

  1. const cat = {
  2. name: 'Pipey',
  3. age: 8,
  4. whatName() {
  5. return this.name
  6. }
  7. };
  8. console.log(cat.whatName()); // => Pipey

方法

  1. const engine = {
  2. // 方法简写,有一个参数
  3. start(adverb) {
  4. console.log(`The engine starts up ${adverb}...`);
  5. },
  6. // 不带参数的匿名箭头函数表达式
  7. sputter: () => {
  8. console.log('The engine sputters...');
  9. },
  10. };
  11. engine.start('noisily');
  12. engine.sputter();

Getters 和 setters

  1. const myCat = {
  2. _name: 'Dottie',
  3. get name() {
  4. return this._name;
  5. },
  6. set name(newName) {
  7. this._name = newName;
  8. }
  9. };
  10. // 引用调用 getter
  11. console.log(myCat.name);
  12. // 赋值调用 setter
  13. myCat.name = 'Yankee';

JavaScript Classes

静态方法/字段

  1. class Dog {
  2. constructor(name) {
  3. this._name = name;
  4. }
  5. introduce() {
  6. console.log('This is ' + this._name + ' !');
  7. }
  8. // 静态方法
  9. static bark() {
  10. console.log('Woof!');
  11. }
  12. static {
  13. console.log('类静态初始化块调用');
  14. }
  15. }
  16. const myDog = new Dog('Buster');
  17. myDog.introduce();
  18. // 调用静态方法
  19. Dog.bark();

公有静态字段

  1. class ClassStaticField {
  2. static staticField = 'static field'
  3. }
  4. console.log(ClassStaticField.staticField)
  5. // 预期输出值:"static field"​

Class

  1. class Song {
  2. constructor() {
  3. this.title;
  4. this.author;
  5. }
  6. play() {
  7. console.log('Song playing!');
  8. }
  9. }
  10. const mySong = new Song();
  11. mySong.play();

extends

  1. // Parent class
  2. class Media {
  3. constructor(info) {
  4. this.publishDate = info.publishDate;
  5. this.name = info.name;
  6. }
  7. }
  8. // Child class
  9. class Song extends Media {
  10. constructor(songData) {
  11. super(songData);
  12. this.artist = songData.artist;
  13. }
  14. }
  15. const mySong = new Song({
  16. artist: 'Queen',
  17. name: 'Bohemian Rhapsody',
  18. publishDate: 1975
  19. });

Class Constructor

  1. class Song {
  2. constructor(title, artist) {
  3. this.title = title;
  4. this.artist = artist;
  5. }
  6. }
  7. const mySong = new Song('Bohemian Rhapsody', 'Queen');
  8. console.log(mySong.title);

Class Methods

  1. class Song {
  2. play() {
  3. console.log('Playing!');
  4. }
  5. stop() {
  6. console.log('Stopping!');
  7. }
  8. }

JavaScript Modules

Export / Import

  1. // myMath.js
  2. // 默认导出 Default export
  3. export default function add(x,y){
  4. return x + y
  5. }
  6. // 正常导出 Normal export
  7. export function subtract(x,y){
  8. return x - y
  9. }
  10. // 多重导出 Multiple exports
  11. function multiply(x,y){
  12. return x * y
  13. }
  14. function duplicate(x){
  15. return x * 2
  16. }
  17. export {
  18. multiply, duplicate
  19. }

import 加载模块

  1. // main.js
  2. import add, { subtract, multiply, duplicate } from './myMath.js';
  3. console.log(add(6, 2)); // 8
  4. console.log(subtract(6, 2)) // 4
  5. console.log(multiply(6, 2)); // 12
  6. console.log(duplicate(5)) // 10
  7. // index.html
  8. <script type="module" src="main.js"></script>

Export Module

  1. // myMath.js
  2. function add(x,y){
  3. return x + y
  4. }
  5. function subtract(x,y){
  6. return x - y
  7. }
  8. function multiply(x,y){
  9. return x * y
  10. }
  11. function duplicate(x){
  12. return x * 2
  13. }
  14. // node.js 中的多个导出
  15. module.exports = {
  16. add,
  17. subtract,
  18. multiply,
  19. duplicate
  20. }

require 加载模块

  1. // main.js
  2. const myMath = require('./myMath.js')
  3. console.log(myMath.add(6, 2)); // 8
  4. console.log(myMath.subtract(6, 2)) // 4
  5. console.log(myMath.multiply(6, 2)); // 12
  6. console.log(myMath.duplicate(5)) // 10

JavaScript Promises

Promise

创建 promises

  1. new Promise((resolve, reject) => {
  2. if (ok) {
  3. resolve(result)
  4. } else {
  5. reject(error)
  6. }
  7. })

使用 promises

  1. promise
  2. .then((result) => { ··· })
  3. .catch((error) => { ··· })

Promise 方法

  1. Promise.all(···)
  2. Promise.race(···)
  3. Promise.reject(···)
  4. Promise.resolve(···)

执行器函数

  1. const executorFn = (resolve, reject) => {
  2. resolve('Resolved!');
  3. };
  4. const promise = new Promise(executorFn);

setTimeout()

  1. const loginAlert = () => {
  2. console.log('Login');
  3. };
  4. setTimeout(loginAlert, 6000);

Promise 状态

  1. const promise = new Promise((resolve, reject) => {
  2. const res = true;
  3. // 一个异步操作。
  4. if (res) {
  5. resolve('Resolved!');
  6. }
  7. else {
  8. reject(Error('Error'));
  9. }
  10. });
  11. promise.then(
  12. (res) => console.log(res),
  13. (err) => console.error(err)
  14. );

.then() 方法

  1. const promise = new Promise((resolve, reject) => {
  2. setTimeout(() => {
  3. resolve('Result');
  4. }, 200);
  5. });
  6. promise.then((res) => {
  7. console.log(res);
  8. }, (err) => {
  9. console.error(err);
  10. });

.catch() 方法

  1. const promise = new Promise(
  2. (resolve, reject) => {
  3. setTimeout(() => {
  4. reject(Error('Promise 无条件拒绝。'));
  5. }, 1000);
  6. });
  7. promise.then((res) => {
  8. console.log(value);
  9. });
  10. promise.catch((err) => {
  11. console.error(err);
  12. });

Promise.all()

  1. const promise1 = new Promise((resolve, reject) => {
  2. setTimeout(() => {
  3. resolve(3);
  4. }, 300);
  5. });
  6. const promise2 = new Promise((resolve, reject) => {
  7. setTimeout(() => {
  8. resolve(2);
  9. }, 200);
  10. });
  11. Promise.all([promise1, promise2]).then((res) => {
  12. console.log(res[0]);
  13. console.log(res[1]);
  14. });

链接多个 .then()

  1. const promise = new Promise(
  2. resolve =>
  3. setTimeout(() => resolve('dAlan'),100)
  4. );
  5. promise.then(res => {
  6. return res === 'Alan'
  7. ? Promise.resolve('Hey Alan!')
  8. : Promise.reject('Who are you?')
  9. })
  10. .then((res) => {
  11. console.log(res)
  12. }, (err) => {
  13. console.error(err)
  14. });

避免嵌套的 Promise 和 .then()

  1. const promise = new Promise((resolve, reject) => {
  2. setTimeout(() => {
  3. resolve('*');
  4. }, 1000);
  5. });
  6. const twoStars = (star) => {
  7. return (star + star);
  8. };
  9. const oneDot = (star) => {
  10. return (star + '.');
  11. };
  12. const print = (val) => {
  13. console.log(val);
  14. };
  15. // 将它们链接在一起
  16. promise.then(twoStars).then(oneDot).then(print);

JavaScript Async-Await

异步

  1. function helloWorld() {
  2. return new Promise(resolve => {
  3. setTimeout(() => {
  4. resolve('Hello World!');
  5. }, 2000);
  6. });
  7. }
  8. // 异步函数表达式
  9. const msg = async function() {
  10. const msg = await helloWorld();
  11. console.log('Message:', msg);
  12. }
  13. // 异步箭头函数
  14. const msg1 = async () => {
  15. const msg = await helloWorld();
  16. console.log('Message:', msg);
  17. }
  18. msg(); // Message: Hello World! <-- 2 秒后
  19. msg1(); // Message: Hello World! <-- 2 秒后

解决 Promises

  1. let pro1 = Promise.resolve(5);
  2. let pro2 = 44;
  3. let pro3 = new Promise(function(resolve, reject) {
  4. setTimeout(resolve, 100, 'foo');
  5. });
  6. Promise.all([pro1, pro2, pro3]).then(function(values) {
  7. console.log(values);
  8. });
  9. // expected => Array [5, 44, "foo"]

异步等待 Promises

  1. function helloWorld() {
  2. return new Promise(resolve => {
  3. setTimeout(() => {
  4. resolve('Hello World!');
  5. }, 2000);
  6. });
  7. }
  8. async function msg() {
  9. const msg = await helloWorld();
  10. console.log('Message:', msg);
  11. }
  12. msg(); // Message: Hello World! <-- 2 秒后

错误处理

  1. // 数据不完整
  2. let json = '{ "age": 30 }';
  3. try {
  4. let user = JSON.parse(json); // <-- 没有错误
  5. console.log( user.name ); // no name!
  6. } catch (e) {
  7. console.error( "Invalid JSON data!" );
  8. }

异步等待运算符

  1. function helloWorld() {
  2. return new Promise(resolve => {
  3. setTimeout(() => {
  4. resolve('Hello World!');
  5. }, 2000);
  6. });
  7. }
  8. async function msg() {
  9. const msg = await helloWorld();
  10. console.log('Message:', msg);
  11. }
  12. msg(); // Message: Hello World! <-- 2 秒后

JavaScript 请求

JSON

  1. const jsonObj = {
  2. "name": "Rick",
  3. "id": "11A",
  4. "level": 4
  5. };

另见:JSON 备忘单

XMLHttpRequest

  1. const xhr = new XMLHttpRequest();
  2. xhr.open('GET', 'mysite.com/getjson');

XMLHttpRequest 是一个浏览器级别的 API,它使客户端能够通过 JavaScript 编写数据传输脚本,而不是 JavaScript 语言的一部分。

GET

  1. const req = new XMLHttpRequest();
  2. req.responseType = 'json';
  3. req.open('GET', '/getdata?id=65');
  4. req.onload = () => {
  5. console.log(xhr.response);
  6. };
  7. req.send();

POST

  1. const data = { weight: '1.5 KG' };
  2. const xhr = new XMLHttpRequest();
  3. // 初始化一个请求。
  4. xhr.open('POST', '/inventory/add');
  5. // 一个用于定义响应类型的枚举值
  6. xhr.responseType = 'json';
  7. // 发送请求以及数据。
  8. xhr.send(JSON.stringify(data));
  9. // 请求成功完成时触发。
  10. xhr.onload = () => {
  11. console.log(xhr.response);
  12. }
  13. // 当 request 遭遇错误时触发。
  14. xhr.onerror = () => {
  15. console.log(xhr.response);
  16. }

fetch api

  1. fetch(url, {
  2. method: 'POST',
  3. headers: {
  4. 'Content-type': 'application/json',
  5. 'apikey': apiKey
  6. },
  7. body: data
  8. }).then(response => {
  9. if (response.ok) {
  10. return response.json();
  11. }
  12. throw new Error('Request failed!');
  13. }, networkError => {
  14. console.log(networkError.message)
  15. })

JSON 格式

  1. fetch('url-that-returns-JSON')
  2. .then(response => response.json())
  3. .then(jsonResponse => {
  4. console.log(jsonResponse);
  5. });

promise url 参数获取 API

  1. fetch('url')
  2. .then(response => {
  3. console.log(response);
  4. }, rejection => {
  5. console.error(rejection.message);
  6. });

Fetch API 函数

  1. fetch('https://api-xxx.com/endpoint', {
  2. method: 'POST',
  3. body: JSON.stringify({id: "200"})
  4. }).then(response => {
  5. if(response.ok){
  6. return response.json();
  7. }
  8. throw new Error('Request failed!');
  9. }, networkError => {
  10. console.log(networkError.message);
  11. }).then(jsonResponse => {
  12. console.log(jsonResponse);
  13. })

async await 语法

  1. const getSuggestions = async () => {
  2. const wordQuery = inputField.value;
  3. const endpoint = `${url}${queryParams}${wordQuery}`;
  4. try{
  5. const response = await fetch(endpoint, {cache: 'no-cache'});
  6. if(response.ok){
  7. const jsonResponse = await response.json()
  8. }
  9. }
  10. catch(error){
  11. console.log(error)
  12. }
  13. }