JavaScript 语法

精选 JavaScript 语法 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。 JavaScript 最核心概念、内置函数、数组/对象方法速查备忘单,初学者完整极速参考指南。

#入门指南

#概述 (Introduction)

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

#控制台打印 (Console)

// => Hello world!
console.log('Hello world!');

// => Hello WarpNav
console.warn('hello %s', 'WarpNav');

// 在 stderr 中打印错误异常
console.error(new Error('出错了!'));

#数字类型 (Numbers)

let amount = 6;
let price = 4.99;

#变量声明 (Variables)

let x = null;
let name = 'Tammy';
const found = false;

// => Tammy, false, null
console.log(name, found, x);

var a;
console.log(a); // => undefined (未定义)

#字符串与模板字面量 (Strings)

let singleQuotes = '单引号字符串';
let doubleQuotes = "双引号字符串";
// 反引号模板字符串用于嵌入表达式或创建多行文本
let backTicks = `模板字符串: ${some_value}`;

// 混合拼接
let mixedQuotes = `hello ${'dear' + name}, "美好的���天`;

// => 21 (字符串长度)
console.log(singleQuotes.length);

#算术运算符 (Arithmetic Operators)

5 + 5 = 10     // 加法 (Addition)
10 - 5 = 5     // 减法 (Subtraction)
5 * 10 = 50    // Multiplication
10 / 5 = 2     // Division
10 % 5 = 0     // Modulo

#代码注释 (Comments)

// This line will denote a comment

/*
The below configuration must be
changed before deployment.
*/

#赋值运算符 (Assignment Operators)

let number = 100;

// Both statements will add 10
number = number + 10;
number += 10;

console.log(number);
// => 120

#字符串插值 (String Interpolation)

let age = 7;

// String concatenation
'Tommy is ' + age + ' years old.';

// String interpolation
`Tommy is ${age} years old.`;

#let 关键字 (let Keyword)

let count;
console.log(count); // => undefined
count = 10;
console.log(count); // => 10

#const 关键字 (const Keyword)

const numberOfColumns = 4;

// TypeError: Assignment to constant...
numberOfColumns = 8;

#JavaScript 条件控制语句

#if 条件判断 (if Statement)

const isMailSent = true;

if (isMailSent) {
  console.log('Mail sent to recipient');
}

#三元运算符 (Ternary Operator)

// The ternary operator is a concise way to write an if-else statement in a single line: condition ? exprIfTrue : exprIfFalse.

var x = 1;

// true, (condition) ? value_if_true : value_if_false
result = x == 1 ? true : false;

#运算符列表 (Operators)

true || false; // true
10 > 5 || 10 > 20; // true
false || false; // false
10 > 100 || 10 > 20; // false

#Logical Operator &&

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

#Comparison Operators

1 > 3; // false
3 > 1; // true
250 >= 250; // true
1 === 1; // true
1 === 2; // false
1 === '1'; // false

#Logical Operator !

let lateToWork = true;
let oppositeValue = !lateToWork;

// => false
console.log(oppositeValue);

#Nullish coalescing operator ??

null ?? 'I win'; //  'I win'
undefined ?? 'Me too'; //  'Me too'

false ?? 'I lose'; //  false
0 ?? 'I lose again'; //  0
'' ?? 'Damn it'; //  ''

#可选 Chaining ?.

const obj = {
  name: 'John Doe',
  age: 8
};

console.log(obj?.address);

#else if 多分支条件 多分支条件 多分支条件 多分支条件 多分支条件 多分支条件 多分支条件 多分支条件 多分支条件 多分支条件 多分支条件 多分支条件 多分支条件 多分支条件 多分支条件 多分支��件 多分支条件

const size = 10;

if (size > 100) {
  console.log('Big');
} else if (size > 20) {
  console.log('Medium');
} else if (size > 4) {
  console.log('Small');
} else {
  console.log('Tiny');
}
// Print: Small

#switch 分支语句 分支语句 分支语句 分支语句 分支语句 分支语句 分支语句 分支语句 分支语句 分支语句 分支语句 分支语句 分支语句 分支语句 分支语句 Statement

const food = 'salad';

switch (food) {
  case 'oyster':
    console.log('The taste of the sea');
    break;
  case 'pizza':
    console.log('A delicious pie');
    break;
  default:
    console.log('Enjoy your meal');
}

#对象查表优化 (Object Lookup)

const food = 'salad';

const foods = {
  oyster: 'The taste of the sea',
  pizza: 'A delicious pie'
};

console.log(foods[food] || 'Enjoy your meal');

#== 与 === 比较运算符区别

0 == false; // true
0 === false; // false, different type
1 == '1'; // true,  automatic type conversion
1 === '1'; // false, different type
null == undefined; // true
null === undefined; // false
'0' == false; // true
'0' === false; // false

The == just check the value, === check both the value and the type.

#JavaScript 函数高级用法

#自定义函数 (Functions)

// Defining the function:
function sum(num1, num2) {
  return num1 + num2;
}

// Calling the function:
sum(3, 6); // 9

#匿名函数 (Anonymous Functions)

// Named function
function rocketToMars() {
  return 'BOOM!';
}

// Anonymous function
const rocketToMars = function () {
  return 'BOOM!';
};

#箭头函数 (Arrow Functions)

#With two arguments

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

#With no arguments

const printHello = () => {
  console.log('hello');
};
printHello(); // => hello

#With a single argument

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

#Concise arrow functions

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

Arrow function available starting ES2015

#return 返回关键字

// With return
function sum(num1, num2) {
  return num1 + num2;
}

// The function doesn't output the sum
function sum(num1, num2) {
  num1 + num2;
}

#函数调用 (Calling Functions)

// Defining the function
function sum(num1, num2) {
  return num1 + num2;
}

// Calling the function
sum(2, 4); // 6

#函数表达式 (Function Expressions)

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

#函数参数 (Function Parameters)

// The parameter is name
function sayHello(name) {
  return `Hello, ${name}!`;
}

#函数声明 (Function Declaration)

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

#JavaScript 作用域 (Scope)

#作用域概念 (Scope)

function myFunction() {
  var pizzaName = 'Margarita';
  // Code here can use pizzaName
}

// Code here can't use pizzaName

#块级作用域变量

const isLoggedIn = true;

if (isLoggedIn == true) {
  const statusMessage = 'Logged in.';
}

// Uncaught ReferenceError...
console.log(statusMessage);

#全局变量 (Global Variables)

// Variable declared globally
const color = 'blue';

function printColor() {
  console.log(color);
}

printColor(); // => blue

#let 与 var 区别对比

for (let i = 0; i < 3; i++) {
  // This is the Max Scope for 'let'
  // i accessible ✔️
}
// i not accessible ❌

for (var i = 0; i < 3; i++) {
  // i accessible ✔️
}
// i accessible ✔️

var is scoped to the nearest function block, and let is scoped to the nearest enclosing block.

#循环与闭包 (Loops with Closures)

// Prints 3 thrice, not what we meant.
for (var i = 0; i < 3; i++) {
  setTimeout(_ => console.log(i), 10);
}

// Prints 0, 1 and 2, as expected.
for (let j = 0; j < 3; j++) {
  setTimeout(_ => console.log(j), 10);
}

The variable has its own copy using let, and the variable has shared copy using var.

#JavaScript 数组常用操作

#数组操作 (Arrays)

const fruits = ['apple', 'orange', 'banana'];

// Different data types
const data = [1, 'chicken', false];

#.length 数组长度属性

const numbers = [1, 2, 3, 4];

numbers.length; // 4

#数组索引访问 (Index)

// Accessing an array element
const myArray = [100, 200, 300];

console.log(myArray[0]); // 100
console.log(myArray[1]); // 200

#数组可变性图解

add remove start end
push
pop
unshift
shift

#Array.push() 尾部追加 尾部追加 尾部追加 尾部追加 尾部追加 尾部追加 尾部追加 尾部追加 尾部追加 尾部追加 尾部追加 尾部追加 尾部追加 尾部追加 尾部追加

// Adding a single element:
const cart = ['apple', 'orange'];
cart.push('pear');

// Adding multiple elements:
const numbers = [1, 2];
numbers.push(3, 4, 5);

Add items to the end and returns the new array length.

#Array.pop() 尾部弹出 尾部弹出 尾部弹出 尾部弹出 尾部弹出 尾部弹出 尾部弹出 尾部弹出 尾部弹出 尾部弹出 尾部弹出 尾部弹出 尾部弹出 尾部弹出 尾部弹出

const fruits = ['apple', 'orange', 'banana'];

const fruit = fruits.pop(); // 'banana'
console.log(fruits); // ["apple", "orange"]

Remove an item from the end and returns the removed item.

#Array.shift() 头部弹出 头部弹出 头部弹出 头部弹出 头部弹出 头部弹出 头部弹出 头部弹出 头部弹出 头部弹出 头部弹出 头部弹出 头部弹出 头部弹出 头部弹出 头部��出 头部弹出

let cats = ['Bob', 'Willy', 'Mini'];

cats.shift(); // ['Willy', 'Mini']

Remove an item from the beginning and returns the removed item.

#Array.unshift() 头部插入 头部插入 头部插入 头部插入 头部插入 头部插入 头部插入 头部插入 头部插入 头部插入 头部插入 头部插入 头部插入 头部插入 头部插入

let cats = ['Bob'];

// => ['Willy', 'Bob']
cats.unshift('Willy');

// => ['Puff', 'George', 'Willy', 'Bob']
cats.unshift('Puff', 'George');

Add items to the beginning and returns the new array length.

#Array.concat() 数组合并 数组合并 数组合并 数组合并 数组合并 数组合并 数组合并 数组合并 数组合并 数组合并 数组合并 数组合并 数组合并 数组合并 数组合并 数���合并 数组合并

const numbers = [3, 2, 1];
const newFirstNumber = 4;

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

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

If you want to avoid mutating your original array, you can use concat.

#数组解构赋值 (Destructuring)

const [name, age] = ['John Doe', 8];

console.log(name);
console.log(age);

#JavaScript Set 集合对象 集合对象 集合对象 集合对象 集合对象 集合对象 集合对象 集合对象 集合对象 集合对象 集合对象 集合对象 集合对象 集合对象 集合对象

#创建 Set 集合

// Empty Set Object
const emptySet = new Set();

// Set Object with values
const setObj = new Set([1, true, 'hi']);

#添加元素 add()

const emptySet = new Set();

// add values
emptySet.add('a'); // 'a'
emptySet.add(1); // 'a', 1
emptySet.add(true); // 'a', 1, true
emptySet.add('a'); // 'a', 1, true

#删除文本对象 (Delete)

const emptySet = new Set([1, true, 'a']);

// delete values
emptySet.delete('a'); // 1, true
emptySet.delete(true); // 1
emptySet.delete(1); //

#存在性检查 has()

const setObj = new Set([1, true, 'a']);

// returns true or false
setObj.has('a'); // true
setObj.has(1); // true
setObj.has(false); // false

#清空集合 clear()

const setObj = new Set([1, true, 'a']);

// clears the set
console.log(setObj); // 1, true, 'a'
setObj.clear(); //

#集合元素数量 size

const setObj = new Set([1, true, 'a']);

consoloe.log(setObj.size); // 3

#集合遍历 forEach

const setObj = new Set([1, true, 'a']);

setObj.forEach(function (value) {
  console.log(value);
});

// 1
// true
// 'a'

#JavaScript 循环语句

#while 循环

while (condition) {
  // code block to be executed
}

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

#倒序循环

const fruits = ['apple', 'orange', 'banana'];

for (let i = fruits.length - 1; i >= 0; i--) {
  console.log(`${i}. ${fruits[i]}`);
}

// => 2. banana
// => 1. orange
// => 0. apple

#do...while 循环

x = 0;
i = 0;

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

#for 基础循环

for (let i = 0; i < 4; i += 1) {
  console.log(i);
}

// => 0, 1, 2, 3

#遍历数组 (Looping Through Arrays)

for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

// => Every item in the array

#break 退出循环

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

#continue 跳过本次

for (i = 0; i < 10; i++) {
  if (i === 3) {
    continue;
  }
  text += 'The number is ' + i + '<br>';
}

#嵌套循环 (Nested Loops)

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

#C 风格 for 循环n loop

const fruits = ['apple', 'orange', 'banana'];

// 1. Print only indexes
for (let index in fruits) {
  console.log(index);
}
// => 0
// => 1
// => 2

// 2. Print only values
for (let index in fruits) {
  console.log(fruits[index]);
}
// => apple
// => orange
// => banana

// 3. Print index with value
for (let index in fruits) {
  console.log(index, fruits[index]);
}
// => 0 apple
// => 1 orange
// => 2 banana

#for...of 迭代器循环

const fruits = ['apple', 'orange', 'banana'];

for (let fruit of fruits) {
  console.log(fruit);
}
// => apple
// => orange
// => banana

for (let [index, value] of fruits.entries()) {
  console.log(index, value);
}
// => 0 apple
// => 1 orange
// => 2 banana

#JavaScript 迭代器与高阶函数

#自定义函数 (Functions) Assigned to Variables

let plusFive = (number) => {
  return number + 5;
};
// f is assigned the value of plusFive
let f = plusFive;

plusFive(3); // 8
// Since f has a function value, it can be invoked.
f(9); // 14

#回调函数 (Callback Functions)

const isEven = (n) => {
  return n % 2 == 0;
};

let printMsg = (evenFunc, num) => {
  const isNumEven = evenFunc(num);
  console.log(`${num} is an even number: ${isNumEven}.`);
};

// Pass in isEven as the callback function
printMsg(isEven, 4);
// => 4 is an even number: True.

#Array.reduce() 数组归约 数组归约 数组归约 数组归约 数组归约 数组归约 数组归约 数组归约 数组归约 数组归约 数组归约 数组归约 数组归约 数组归约 数组归约

const numbers = [1, 2, 3, 4];

const sum = numbers.reduce((accumulator, curVal) => {
  return accumulator + curVal;
});

console.log(sum); // 10

#Array.map() 数组映射 数组映射 数组映射 数组映射 数组映射 数组映射 数组映射 数组映射 数组映射 数组映射 数组映射 数组映射 数组映射 数组映射 数组映射

const members = ['Taylor', 'Donald', 'Don', 'Natasha', 'Bobby'];

const announcements = members.map((member) => {
  return member + ' joined the contest.';
});

console.log(announcements);

#Array.forEach() 数组遍历 数组遍历 数组遍历 数组遍历 数组遍历 数组遍历 数组遍历 数组遍历 数组遍历 数组遍历 数组遍历 数组遍历 数组遍历 数组遍历 数组遍历

const numbers = [28, 77, 45, 99, 27];

numbers.forEach((number) => {
  console.log(number);
});

#Array.filter() 数组过滤 数组过滤 数组过滤 数组过滤 数组过滤 数组过滤 数组过滤 数组过滤 数组过滤 数组过滤 数组过滤 数组过滤 数组过滤 数组过滤 数组过滤

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

#JavaScript 对象 (Objects)

#访问对象属性

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

#属性命名规则

// Example of invalid key names
const trainSchedule = {
  // Invalid because of the space between words.
  platform num: 10,
  // Expressions cannot be keys.
  40 - 10 + 2: 30,
  // A + sign is invalid unless it is enclosed in quotations.
  +compartment: 'C'
}

#不存在的属性访问

const classElection = {
  date: 'January 12'
};

console.log(classElection.place); // undefined

#对象属性修改

const student = {
  name: 'Sheldon',
  score: 100,
  grade: 'A'
};

console.log(student);
// { name: 'Sheldon', score: 100, grade: 'A' }

delete student.score;
student.grade = 'F';
console.log(student);
// { name: 'Sheldon', grade: 'F' }

student = {};
// TypeError: Assignment to constant variable.

#属性简写语法

const person = {
  name: 'Tom',
  age: '22'
};
const { name, age } = person;
console.log(name); // 'Tom'
console.log(age); // '22'

#删除文本对象 (Delete) operator

const person = {
  firstName: 'Matilda',
  age: 27,
  hobby: 'knitting',
  goal: 'learning JavaScript'
};

delete person.hobby; // or delete person[hobby];

console.log(person);
/*
{
  firstName: "Matilda"
  age: 27
  goal: "learning JavaScript"
}
*/

#对象作为函数参数

const origNum = 8;
const origObj = { color: 'blue' };

const changeItUp = (num, obj) => {
  num = 7;
  obj.color = 'red';
};

changeItUp(origNum, origObj);

// Will output 8 since integers are passed by value.
console.log(origNum);

// Will output 'red' since objects are passed
// by reference and are therefore mutable.
console.log(origObj.color);

#对象简写创建方式

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

#this 关键字上下文

const cat = {
  name: 'Pipey',
  age: 8,
  whatName() {
    return this.name;
  }
};
console.log(cat.whatName()); // => Pipey

#工厂函数创建对象

// A factory function that accepts 'name',
// 'age', and 'breed' parameters to return
// a customized dog object.
const dogFactory = (name, age, breed) => {
  return {
    name: name,
    age: age,
    breed: breed,
    bark() {
      console.log('Woof!');
    }
  };
};

#对象方法定义

const engine = {
  // method shorthand, with one argument
  start(adverb) {
    console.log(`The engine starts up ${adverb}...`);
  },
  // anonymous arrow function expression with no arguments
  sputter: () => {
    console.log('The engine sputters...');
  }
};

engine.start('noisily');
engine.sputter();

#Getter 与 Setter 属性器

const myCat = {
  _name: 'Dottie',
  get name() {
    return this._name;
  },
  set name(newName) {
    this._name = newName;
  }
};

// Reference invokes the getter
console.log(myCat.name);

// Assignment invokes the setter
myCat.name = 'Yankee';

#数组解构赋值 (Destructuring)

const obj = {
  name: 'John Doe',
  age: 8
};

const { name, age } = obj;

console.log(name);
console.log(age);

#JavaScript 面向对象类 (Classes)

#静态方法 (Static Methods)

class Dog {
  constructor(name) {
    this._name = name;
  }

  introduce() {
    console.log('This is ' + this._name + ' !');
  }

  // A static method
  static bark() {
    console.log('Woof!');
  }
}

const myDog = new Dog('Buster');
myDog.introduce();

// Calling the static method
Dog.bark();

#Class 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声�� 类的声明

class Song {
  constructor() {
    this.title;
    this.author;
  }

  play() {
    console.log('Song playing!');
  }
}

const mySong = new Song();
mySong.play();

#Class 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 Constructor

class Song {
  constructor(title, artist) {
    this.title = title;
    this.artist = artist;
  }
}

const mySong = new Song('Bohemian Rhapsody', 'Queen');
console.log(mySong.title);

#Class 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 类的声明 Methods

class Song {
  play() {
    console.log('Playing!');
  }

  stop() {
    console.log('Stopping!');
  }
}

#类继承 (extends)

// Parent class
class Media {
  constructor(info) {
    this.publishDate = info.publishDate;
    this.name = info.name;
  }
}

// Child class
class Song extends Media {
  constructor(songData) {
    super(songData);
    this.artist = songData.artist;
  }
}

const mySong = new Song({
  artist: 'Queen',
  name: 'Bohemian Rhapsody',
  publishDate: 1975
});

#JavaScript 模块化 (Modules)

#导出模块 (Export)

// myMath.js

// Default export
export default function add(x, y) {
  return x + y;
}

// Normal export
export function subtract(x, y) {
  return x - y;
}

// Multiple exports
function multiply(x, y) {
  return x * y;
}
function duplicate(x) {
  return x * 2;
}
export { multiply, duplicate };

#导入模块 (Import)

// main.js
import add, { subtract, multiply, duplicate } from './myMath.js';

console.log(add(6, 2)); // 8
console.log(subtract(6, 2)) // 4
console.log(multiply(6, 2)); // 12
console.log(duplicate(5)) // 10

// index.html
<script type="module" src="main.js"></script>

#导出模块 (Export) Module

// myMath.js

function add(x, y) {
  return x + y;
}
function subtract(x, y) {
  return x - y;
}
function multiply(x, y) {
  return x * y;
}
function duplicate(x) {
  return x * 2;
}

// Multiple exports in node.js
module.exports = {
  add,
  subtract,
  multiply,
  duplicate
};

#CommonJS require() 模块导入 模块导入 模块导入 模块导入 模块导入 模块导入 模块导入 模块导入 模块导入 模块导入 模块导入 模块导入 模块导入 模块导入 模块导入

// main.js
const myMath = require('./myMath.js');

console.log(myMath.add(6, 2)); // 8
console.log(myMath.subtract(6, 2)); // 4
console.log(myMath.multiply(6, 2)); // 12
console.log(myMath.duplicate(5)); // 10

#JavaScript Promise 异步编程

#Promise 三种状态

const promise = new Promise((resolve, reject) => {
  const res = true;
  // An asynchronous operation.
  if (res) {
    resolve('Resolved!');
  } else {
    reject(Error('Error'));
  }
});

promise.then(
  (res) => console.log(res),
  (err) => console.error(err)
);

#执行器函数 (Executor)

const executorFn = (resolve, reject) => {
  resolve('Resolved!');
};

const promise = new Promise(executorFn);

#setTimeout 定时器

const loginAlert = () => {
  console.log('Login');
};

setTimeout(loginAlert, 6000);

#.then() 链式回调

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Result');
  }, 200);
});

promise.then(
  (res) => {
    console.log(res);
  },
  (err) => {
    console.error(err);
  }
);

#Promise.catch() 捕获异常 捕获异常 捕获异常 捕获异常 捕获异常 捕获异常 捕获异常 捕获异常 捕获异常 捕获异常 捕获异常 捕获异常 捕获异常 捕获异常 捕获异常 捕获异��� 捕获异常

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject(Error('Promise Rejected Unconditionally.'));
  }, 1000);
});

promise.then((res) => {
  console.log(value);
});

promise.catch((err) => {
  console.error(err);
});

#Promise.all() 并发等待 并发等待 并发等待 并发等待 并发等待 并发等待 并发等待 并发等待 并发等待 并发等待 并发等待 并发等待 并发等待 并发等待 并发等待

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(3);
  }, 300);
});
const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(2);
  }, 200);
});

Promise.all([promise1, promise2]).then((res) => {
  console.log(res[0]);
  console.log(res[1]);
});

#Promise.allSettled() 汇总结果 汇总结果 汇总结果 汇总结果 汇总结果 汇总结果 汇总结果 汇总结果 汇总结果 汇总结果 汇总结果 汇总结果 汇总结果 汇总结果 汇总结果

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject(2);
  }, 100);
});

Promise.allSettled([promise1, promise2]).then((res) => {
  console.log(res[0].status);
  console.log(res[1].status);
});

#避免 Promise 地狱

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('*');
  }, 1000);
});

const twoStars = (star) => {
  return star + star;
};

const oneDot = (star) => {
  return star + '.';
};

const print = (val) => {
  console.log(val);
};

// Chaining them all together
promise.then(twoStars).then(oneDot).then(print);

#创建 Promise 实例

const executorFn = (resolve, reject) => {
  console.log('The executor function of the promise!');
};

const promise = new Promise(executorFn);

#链式调用 .then()

const promise = new Promise((resolve) =>
  setTimeout(() => resolve('dAlan'), 100)
);

promise
  .then((res) => {
    return res === 'Alan'
      ? Promise.resolve('Hey Alan!')
      : Promise.reject('Who are you?');
  })
  .then(
    (res) => {
      console.log(res);
    },
    (err) => {
      console.error(err);
    }
  );

#模拟 Promise HTTP 请求

const mock = (success, timeout = 1000) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (success) {
        resolve({ status: 200, data: {} });
      } else {
        reject({ message: 'Error' });
      }
    }, timeout);
  });
};
const someEvent = async () => {
  try {
    await mock(true, 1000);
  } catch (e) {
    console.log(e.message);
  }
};

#🚀 JavaScript Async/Await 异步终极方案 异步终极方案

#异步执行原理

function helloWorld() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Hello World!');
    }, 2000);
  });
}

const msg = async function () {
  //Async Function Expression
  const msg = await helloWorld();
  console.log('Message:', msg);
};

const msg1 = async () => {
  //Async Arrow Function
  const msg = await helloWorld();
  console.log('Message:', msg);
};

msg(); // Message: Hello World! <-- after 2 seconds
msg1(); // Message: Hello World! <-- after 2 seconds

#解析 Promise 结果

let pro1 = Promise.resolve(5);
let pro2 = 44;
let pro3 = new Promise(function (resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([pro1, pro2, pro3]).then(function (values) {
  console.log(values);
});
// expected => Array [5, 44, "foo"]

#async/await 配合 Promise

function helloWorld() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Hello World!');
    }, 2000);
  });
}

async function msg() {
  const msg = await helloWorld();
  console.log('Message:', msg);
}

msg(); // Message: Hello World! <-- after 2 seconds

#异常捕获 try/catch

let json = '{ "age": 30 }'; // incomplete data

try {
  let user = JSON.parse(json); // <-- no errors
  console.log(user.name); // no name!
} catch (e) {
  console.error('Invalid JSON data!');
}

#await 运算符用法

function helloWorld() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Hello World!');
    }, 2000);
  });
}

async function msg() {
  const msg = await helloWorld();
  console.log('Message:', msg);
}

msg(); // Message: Hello World! <-- after 2 seconds

#JavaScript HTTP 请求���全

#JSON 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON)

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

Also see: JSON cheatsheet

#Ajax / XMLHttpRequest 网络请求

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

XMLHttpRequest is a browser-level API that enables the client to script data transfers via JavaScript, NOT part of the JavaScript language.

#GET 请求示例 请求示例 请求示例 请求示例 请求示例 请求示例 请求示例 请求示例 请求示例 请求示例 请求示例 请求示例 请求示例 请求示例 请求示例

const req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', '/getdata?id=65');
req.onload = () => {
  console.log(xhr.response);
};

req.send();

#POST 请求示例

const data = {
  fish: 'Salmon',
  weight: '1.5 KG',
  units: 5
};
const xhr = new XMLHttpRequest();
xhr.open('POST', '/inventory/add');
xhr.responseType = 'json';
xhr.send(JSON.stringify(data));

xhr.onload = () => {
  console.log(xhr.response);
};

#Fetch API 现��化请求

fetch(url, {
    method: 'POST',
    headers: {
      'Content-type': 'application/json',
      'apikey': apiKey
    },
    body: data
  }).then(response => {
    if (response.ok) {
      return response.json();
    }
    throw new Error('Request failed!');
  }, networkError => {
    console.log(networkError.message)
  })
}

#JSON 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与���列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) 解析与序列化 (JSON) Formatted

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

#Promise 与 Fetch 组合请求

fetch('url')
.then(
  response  => {
    console.log(response);
  },
 rejection => {
    console.error(rejection.message);
);

#Fetch 封装函数

fetch('https://api-xxx.com/endpoint', {
  method: 'POST',
  body: JSON.stringify({ id: '200' })
})
  .then(
    (response) => {
      if (response.ok) {
        return response.json();
      }
      throw new Error('Request failed!');
    },
    (networkError) => {
      console.log(networkError.message);
    }
  )
  .then((jsonResponse) => {
    console.log(jsonResponse);
  });

#Async / Await 异步语法

const getSuggestions = async () => {
  const wordQuery = inputField.value;
  const endpoint = `${url}${queryParams}${wordQuery}`;
  try {
    const response = await fetch(endpoint, { cache: 'no-cache' });
    if (response.ok) {
      const jsonResponse = await response.json();
    }
  } catch (error) {
    console.log(error);
  }
};