备忘清单


打印调试

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

断点调试

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

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

数字

1let amount = 6;
2let price = 4.99;
3let home = 1e2;
4let num = 1_000_000; // 位数过多可以用 _ 分割
5let m = 0644;   // 八进制数字 420

let 关键字

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

const 关键字

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

变量

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

字符串

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

算术运算符

15 + 5 = 10     // 加法 Addition
210 - 5 = 5     // 减法 Subtraction
35 * 10 = 50    // 乘法 Multiplication
410 / 5 = 2     // 除法 Division
510 % 5 = 0     // 取模 Modulo

注释

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

赋值运算符

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

字符串插值

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

字符串

 1var abc = "abcdefghijklmnopqrstuvwxyz";
 2var esc = 'I don\'t \n know';    // \n 换行
 3var len = abc.length;            // 字符串长度
 4abc.indexOf("lmno");             // 查找子字符串,如果不包含则 -1
 5abc.lastIndexOf("lmno");         // 最后一次出现
 6abc.slice(3, 6);                 // 去掉“def”,负值从后面计算
 7abc.replace("abc","123");        // 查找和替换,接受正则表达式
 8abc.toUpperCase();               // 转换为大写
 9abc.toLowerCase();               // 转换为小写
10abc.concat(" ", str2);           // abc + " " + str2
11abc.charAt(2);                   // 索引处的字符:“c”
12abc[2];                          // 不安全,abc[2] = "C" 不起作用
13// 索引处的字符代码:“c”-> 99
14abc.charCodeAt(2);
15// 用逗号分割字符串给出一个数组
16abc.split(",");
17// 分割字符
18abc.split("");
19// 匹配开头字符串,如果忽略第二个参数,则从索引 0 开始匹配
20abc.startsWith("bc", 1);
21// 匹配结尾的字符串,如果忽略第二个参数,则默认是原字符串长度
22abc.endsWith("wxy", abc.length - 1);
23// padEnd 和 padStart 都用于填充长度,默认填充对象是空格
24"200".padEnd(5); // "200  "
25"200".padEnd(5, "."); // "200.."
26// 重复字符
27"abc".repeat(2); // "abcabc"
28// trim、trimEnd 和 trimStart 用于去除首尾空格
29" ab c ".trim(); // "ab c"
30// 数字转为十六进制 (16)、八进制 (8) 或二进制 (2)
31(128).toString(16);

数字

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

Math

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

全局函数

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

JavaScript 条件

操作符

1true || false;       // true
210 > 5 || 10 > 20;   // true
3false || false;      // false
410 > 100 || 10 > 20; // false

逻辑运算符 &&

1true && true;        // true
21 > 2 && 2 > 1;      // false
3true && false;       // false
44 === 4 && 3 > 1;    // true

比较运算符

11 > 3                 // false
23 > 1                 // true
3250 >= 250            // true
41 === 1               // true
51 === 2               // false
61 === '1'             // false

逻辑运算符

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

空值合并运算符 ??

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

if Statement (if 语句)

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

Ternary Operator (三元运算符)

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

else if

1const size = 10;
2if (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 ===

10 == false     // true
20 === false    // false, 不同类型
31 == "1"       // true,  自动类型转换
41 === "1"      // false, 不同类型
5null == undefined  // true
6null === undefined // false
7'0' == false       // true
8'0' === false      // false

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

switch 语句

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

switch 多 case - 单一操作

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

JavaScript Functions 函数

函数

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

匿名函数

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

箭头函数 (ES6)

有两个参数

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

没有参数

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

只有一个参数

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

简洁箭头函数

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

从 ES2015 开始提供箭头函数

返回关键字

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

调用函数

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

立即执行函数

1//命名函数并立即执行一次
2(function sum(num1, num2) {
3  return num1 + num2;
4})(2,4)//6

函数表达式

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

函数参数

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

函数声明

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

JavaScript 范围

范围

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

{ } 块内声明的变量

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

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

块作用域变量

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

全局变量

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

let vs var

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

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

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

带闭包的循环

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

1// 按预期打印 0、1 和 2。
2for (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 对象 #

数组

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

属性 .length

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

索引

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

可变图表

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

方法 .push()

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

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

方法 .pop()

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

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

方法 .shift()

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

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

方法 .some()

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

方法 .concat()

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

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

方法 .splice()

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

方法 .unshift()

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

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

方法 .filter()

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

JavaScript 循环

While 循环

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

反向循环

1const fruits = ["apple", "dew", "berry"];
2for (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 语句

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

For 循环

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

遍历数组

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

Break

1for (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

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

嵌套循环

1for (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 循环

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

label 语句

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

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

for…of 循环

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

for await…of

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

可选的 for 表达式

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

JavaScript 迭代器(Iterators)

分配给变量的函数

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

回调函数

 1const isEven = (n) => {
 2  return n % 2 == 0;
 3}
 4let 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
 9printMsg(isEven, 4); 
10// => The number 4 is an even number: True.

数组方法 .reduce()

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

数组方法 .map()

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

数组方法 .forEach()

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

数组方法 .filter()

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

JavaScript 对象(Objects)

访问属性

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

命名属性

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

不存在的属性

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

可变的

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

赋值简写语法

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

删除运算符

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

对象作为参数

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

工厂函数

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

速记对象创建

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

this 关键字

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

方法

 1const 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};
11engine.start('noisily');
12engine.sputter();

Getters 和 setters

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

Proxy

Proxy 对象用于创建一个对象的代理,从而实现基本操作的拦截和自定义(如属性查找、赋值、枚举、函数调用等)。

 1// 用于拦截对象的读取属性操作。
 2const handler = {
 3    get: function(obj, prop) {
 4        return prop in obj ? obj[prop] : 37;
 5    }
 6};
 7
 8const p = new Proxy({}, handler);
 9p.a = 1;
10p.b = undefined;
11
12console.log(p.a, p.b);      // 1, undefined
13console.log('c' in p, p.c); // false, 37

语法

1const p = new Proxy(target, handler)
  • target 要使用 Proxy 包装的目标对象(可以是任何类型的对象,包括原生数组,函数,甚至另一个代理)。
  • handler 一个通常以函数作为属性的对象,各属性中的函数分别定义了在执行各种操作时代理 p 的行为。

方法

:- :-
Proxy.revocable() 创建一个可撤销的Proxy对象 #

handler 对象的方法

:- :-
handler.getPrototypeOf() Object.getPrototypeOf 方法的捕捉器 #
handler.setPrototypeOf() Object.setPrototypeOf 方法的捕捉器 #
handler.isExtensible() Object.isExtensible 方法的捕捉器 #
handler.preventExtensions() Object.preventExtensions 方法的捕捉器 #
handler.getOwnPropertyDescriptor() Object.getOwnPropertyDescriptor 方法的捕捉器 #
handler.defineProperty() Object.defineProperty 方法的捕捉器 #
handler.has() in 操作符的捕捉器 #
handler.get() 属性读取操作的捕捉器 #
handler.set() 属性设置操作的捕捉器 #
handler.deleteProperty() delete 操作符的捕捉器 #
handler.ownKeys() Object.getOwnPropertyNames 方法和 Object.getOwnPropertySymbols 方法的捕捉器 #
handler.apply() 函数调用操作的捕捉器 #
handler.construct() new 操作符的捕捉器 #

Reflect

Reflect 是一个内置的对象,它提供拦截 JavaScript 操作的方法。这些方法与proxy handlers (en-US)的方法相同。Reflect不是一个函数对象,因此它是不可构造的。

 1// 检测一个对象是否存在特定属性
 2const duck = {
 3  name: 'Maurice',
 4  color: 'white',
 5  greeting: function() {
 6    console.log(`Quaaaack! My name is ${this.name}`);
 7  }
 8}
 9
10Reflect.has(duck, 'color');
11// true
12Reflect.has(duck, 'haircut');
13// false

静态方法

:- :-
Reflect.apply(target, thisArgument, argumentsList) 对一个函数进行调用操作,同时可以传入一个数组作为调用参数。和 Function.prototype.apply() 功能类似 #
Reflect.construct(target, argumentsList[, newTarget]) 对构造函数进行 new 操作,相当于执行 new target(…args) #
Reflect.defineProperty(target, propertyKey, attributes) 和 Object.defineProperty() 类似。如果设置成功就会返回 true #
Reflect.deleteProperty(target, propertyKey) 作为函数的delete操作符,相当于执行 delete target[name] #
Reflect.get(target, propertyKey[, receiver]) 获取对象身上某个属性的值,类似于 target[name] #
Reflect.getOwnPropertyDescriptor(target, propertyKey) 类似于 Object.getOwnPropertyDescriptor()。如果对象中存在该属性,则返回对应的属性描述符,否则返回 undefined #
Reflect.getPrototypeOf(target) 类似于 Object.getPrototypeOf() #
Reflect.has(target, propertyKey) 判断一个对象是否存在某个属性,和 in 运算符 的功能完全相同 #
Reflect.isExtensible(target) 类似于 Object.isExtensible() #
Reflect.ownKeys(target) 返回一个包含所有自身属性(不包含继承属性)的数组。(类似于 Object.keys(), 但不会受enumerable 影响) #
Reflect.preventExtensions(target) 类似于 Object.preventExtensions()。返回一个Boolean #
Reflect.set(target, propertyKey, value[, receiver]) 将值分配给属性的函数。返回一个Boolean,如果更新成功,则返回true #
Reflect.setPrototypeOf(target, prototype) 设置对象原型的函数。返回一个 Boolean,如果更新成功,则返回 true #

JavaScript this 绑定

隐式绑定

 1function foo() {
 2  console.log(this)
 3}
 4let obj1 = {
 5  name: "obj1",
 6  foo: foo
 7}
 8let obj2 = {
 9  name: "obj2",
10  obj1: obj1
11}
12obj2.obj1.foo() // [Object obj1]

隐式丢失

1let a = obj2.obj1.foo()
2a() // Window
  • 指定隐式绑定:必须在调用的对象内部有一个对函数的引用(比如一个属性)
  • 将以上调用赋值给一个变量,结果最终会是 Window
  • 在 a 被调用的位置没有进行过任何显示绑定,最终全局对象 window 会调用它(Window.a

显示绑定

1function getName(a1, a2) {
2  console.log("此人" + this.name, "岁数" + (a1 + a2))
3}
4let person = {
5  name: "zhangsan"
6}

call

call 第一个参数接受 this 作用域,剩余参数传递给其调用的函数

1getName.call(person, 18, 12)

apply

apply 第一个参数与 call 相同,第二个参数是其调用函数的参数数组

1getName.apply(person, [18, 12])

bind

bind 函数会返回一个新函数

1getName.bind(person,18,12)()
2//或者可以这样
3getName.bind(person)(18, 12)
4//或者这样
5getName.bind(person).bind(null, 18)(12)

内置函数中的 this

数组中的一些方法,类似于 map、forEach 等,可以自己设置绑定 this

1const obj = {
2  name: "zhangsan"
3}
4const array = [1, 2, 3];
5array.map(function(value){
6  console.log(this.name)
7}, obj)
8// zhangsan x3 

其中一些全局对象,如 setTimeout 等,它们和未显示绑定 this 的部分数组方法一样,都会指向全局对象(Window

1setTimeout(function(){ 
2  console.log(this)
3}, 1000) // Window

JavaScript Classes

静态方法/字段

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

公有静态字段

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

Class

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

extends

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

Class Constructor

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

Class Methods

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

JavaScript Modules

Export / Import

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

import 加载模块

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

Export Module

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

require 加载模块

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

JavaScript Promises

Promise

创建 promises

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

使用 promises

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

Promise 方法

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

执行器函数

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

setTimeout()

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

Promise 状态

 1const 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});
11promise.then(
12  (res) => console.log(res),
13  (err) => console.error(err)
14);

.then() 方法

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

.catch() 方法

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

Promise.all()

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

链接多个 .then()

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

避免嵌套的 Promise 和 .then()

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

JavaScript Async-Await

异步

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

解决 Promises

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

异步等待 Promises

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

错误处理

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

异步等待运算符

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

JavaScript 请求

JSON

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

另见:JSON 备忘单

XMLHttpRequest

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

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

GET

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

POST

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

fetch api

 1fetch(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 格式

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

promise url 参数获取 API

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

Fetch API 函数

 1fetch('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 语法

 1const 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}