包含最重要概念、函数、方法等的 JavaScript 备忘单。 初学者的完整快速参考。
入门 介绍 JavaScript 是一种轻量级的解释型编程语言。
打印调试 1 2 3 4 5 6 console .log ('Hello world!' );console .warn ('hello %s' , 'QuickReference' );console .error (new Error ('Oops!' ));
断点调试 1 2 3 4 function potentiallyBuggyCode ( ) { debugger ; }
debugger 语句调用任何可用的调试功能。
数字 1 2 3 4 5 let amount = 6 ;let price = 4.99 ;let home = 1e2 ;let num = 1_000_000 ; let m = 0644 ;
let 关键字 1 2 3 4 let count; console .log (count); count = 10 ; console .log (count);
const 关键字 1 2 3 const numberOfColumns = 4 ;numberOfColumns = 8 ;
变量 1 2 3 4 5 6 7 let x = null ;let name = "Tammy" ;const found = false ;console .log (name, found, x);var a;console .log (a);
字符串 1 2 3 4 let single = 'Wheres my bandit hat?' ;let double = "Wheres my bandit hat?" ;console .log (single.length );
算术运算符 1 2 3 4 5 5 + 5 = 10 10 - 5 = 5 5 * 10 = 50 10 / 5 = 2 10 % 5 = 0
注释
赋值运算符 1 2 3 4 5 6 let number = 100 ;number = number + 10 ; number += 10 ; console .log (number);
字符串插值 1 2 3 4 5 let age = 7 ;'Tommy is ' + age + ' years old.' ;`Tommy is ${age} years old.` ;
字符串 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 var abc = "abcdefghijklmnopqrstuvwxyz" ;var esc = 'I don\'t \n know' ; var len = abc.length ; abc.indexOf ("lmno" ); abc.lastIndexOf ("lmno" ); abc.slice (3 , 6 ); abc.replace ("abc" ,"123" ); abc.toUpperCase (); abc.toLowerCase (); abc.concat (" " , str2); abc.charAt (2 ); abc[2 ]; abc.charCodeAt (2 ); abc.split ("," ); abc.split ("" ); abc.startsWith ("bc" , 1 ); abc.endsWith ("wxy" , abc.length - 1 ); "200" .padEnd (5 ); "200" .padEnd (5 , "." ); "abc" .repeat (2 ); " ab c " .trim (); (128 ).toString (16 );
数字 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 var pi = 3.141 ;pi.toFixed (0 ); pi.toFixed (2 ); pi.toPrecision (2 ) pi.valueOf (); Number (true ); Number (new Date ()) parseInt ("3 months" ); parseFloat ("3.5 days" ); Number .MAX_VALUE Number .MIN_VALUE Number .NEGATIVE_INFINITY Number .POSITIVE_INFINITY
Math 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 const pi = Math .PI ; Math .round (4.4 ); Math .round (4.5 ); Math .pow (2 ,8 ); Math .sqrt (49 ); Math .abs (-3.14 ); Math .ceil (3.14 ); Math .floor (3.99 ); Math .sin (0 ); Math .cos (Math .PI ); Math .min (0 , 3 , -2 , 2 ); Math .max (0 , 3 , -2 , 2 ); Math .log (1 ); Math .exp (1 ); Math .random (); Math .floor (Math .random () * 5 ) + 1 ;
全局函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 eval (); String (23 ); (23 ).toString (); Number ("23" ); decodeURI (enc); encodeURI (uri); decodeURIComponent (enc); encodeURIComponent (uri); isFinite (); isNaN (); parseFloat (); parseInt ();
JavaScript 条件 操作符 1 2 3 4 true || false ; 10 > 5 || 10 > 20 ; false || false ; 10 > 100 || 10 > 20 ;
逻辑运算符 && 1 2 3 4 true && true ; 1 > 2 && 2 > 1 ; true && false ; 4 === 4 && 3 > 1 ;
比较运算符 1 2 3 4 5 6 1 > 3 3 > 1 250 >= 250 1 === 1 1 === 2 1 === '1'
逻辑运算符 1 2 3 4 let lateToWork = true ;let oppositeValue = !lateToWork;console .log (oppositeValue);
空值合并运算符 ?? 1 2 3 4 5 null ?? 'I win' ; undefined ?? 'Me too' ; false ?? 'I lose' 0 ?? 'I lose again' '' ?? 'Damn it'
if Statement (if 语句) 1 2 3 4 const isMailSent = true ;if (isMailSent) { console .log ('Mail sent to recipient' ); }
Ternary Operator (三元运算符) 1 2 3 4 var age = 1 ;var status = (age >= 18 ) ? true : false ;
else if 1 2 3 4 5 6 7 8 9 const size = 10 ;if (size > 20 ) { console .log ('Medium' ); } else if (size > 4 ) { console .log ('Small' ); } else { console .log ('Tiny' ); }
== vs === 1 2 3 4 5 6 7 8 0 == false 0 === false 1 == "1" 1 === "1" null == undefined null === undefined '0' == false '0' === false
==
只检查值,===
检查值和类型。
switch 语句 1 2 3 4 5 6 7 8 9 10 const food = 'salad' ;switch (food) { case 'oyster' : console .log ('海的味道' ); break ; case 'pizza' : console .log ('美味的馅饼' ); break ; default : console .log ('请您用餐' ); }
switch 多 case - 单一操作 1 2 3 4 5 6 7 8 9 10 const food = 'salad' ;switch (food) { case 'oyster' : case 'pizza' : console .log ('美味的馅饼' ); break ; default : console .log ('请您用餐' ); }
JavaScript Functions 函数 函数 1 2 3 4 5 6 function sum (num1, num2 ) { return num1 + num2; } sum (3 , 6 );
匿名函数 1 2 3 4 5 6 7 8 function rocketToMars ( ) { return 'BOOM!' ; } const rocketToMars = function ( ) { return 'BOOM!' ; }
箭头函数 (ES6) 有两个参数 1 2 3 4 const sum = (param1, param2 ) => { return param1 + param2; }; console .log (sum (2 ,5 ));
没有参数 1 2 3 4 const printHello = ( ) => { console .log ('hello' ); }; printHello ();
只有一个参数 1 2 3 4 const checkWeight = weight => { console .log (`Weight : ${weight} ` ); }; checkWeight (25 );
简洁箭头函数 1 2 3 const multiply = (a, b ) => a * b; console .log (multiply (2 , 30 ));
从 ES2015 开始提供箭头函数
返回关键字 1 2 3 4 5 6 7 8 function sum (num1, num2 ) { return num1 + num2; } function sum (num1, num2 ) { num1 + num2; }
调用函数 1 2 3 4 5 6 function sum (num1, num2 ) { return num1 + num2; } sum (2 , 4 );
立即执行函数 1 2 3 4 (function sum (num1, num2 ) { return num1 + num2; })(2 ,4 )
函数表达式 1 2 3 const dog = function ( ) { return 'Woof!' ; }
函数参数 1 2 3 4 function sayHello (name ) { return `Hello, ${name} !` ; }
函数声明 1 2 3 function add (num1, num2 ) { return num1 + num2; }
JavaScript 范围 范围 1 2 3 4 5 6 function myFunction ( ) { var pizzaName = "Margarita" ; }
{ }
块内声明的变量
1 2 3 4 5 6 7 8 9 { let x = 2 ; } { var x = 2 ; }
1 2 3 var x = 2 ; let x = 2 ; const x = 2 ;
ES6 引入了两个重要的新 JavaScript 关键字:let 和 const。这两个关键字在 JavaScript 中提供了块作用域。
块作用域变量 1 2 3 4 5 6 7 const isLoggedIn = true ;if (isLoggedIn == true ) { const statusMessage = 'Logged in.' ; } console .log (statusMessage);
全局变量 1 2 3 4 5 6 7 const color = 'blue' ;function printColor ( ) { console .log (color); } printColor ();
let
vs var
1 2 3 4 5 for (let i = 0 ; i < 3 ; i++) { }
1 2 3 4 for (var i = 0 ; i < 3 ; i++) { }
var
的范围是最近的函数块,而 let
的范围是最近的封闭块。
带闭包的循环 1 2 3 4 for (var i = 0 ; i < 3 ; i++) { setTimeout (_ => console .log (i), 10 ); }
1 2 3 4 for (let j = 0 ; j < 3 ; j++) { setTimeout (_ => console .log (j), 10 ); }
变量使用 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 2 3 const fruits = ["apple" , "dew" , "banana" ];const data = [1 , 'chicken' , false ];
属性 .length 1 2 const numbers = [1 , 2 , 3 , 4 ];numbers.length
索引 1 2 3 4 const myArray = [100 , 200 , 300 ];console .log (myArray[0 ]); console .log (myArray[1 ]);
可变图表
添加
删除
开始
结束
push
✅
✅
pop
✅
✅
unshift
✅
✅
shift
✅
✅
方法 .push() 1 2 3 4 5 6 const cart = ['apple' , 'orange' ];cart.push ('pear' ); const numbers = [1 , 2 ];numbers.push (3 , 4 , 5 );
将项目添加到末尾 并返回新的数组长度。
方法 .pop() 1 2 3 4 const fruits = ["apple" , "dew" , "banana" ];const fruit = fruits.pop (); console .log (fruits);
从末尾删除 一个项目并返回已删除的项目。
方法 .shift() 1 2 3 4 const array1 = [1 , 2 , 3 ];const firstElement = array1.shift ();console .log (array1); console .log (firstElement);
从头删除 一个项目并返回已删除的项目。
方法 .some() 1 2 3 4 5 const array = [1 , 2 , 3 , 4 , 5 ];const even = (element ) => element % 2 === 0 ;console .log (array.some (even));
方法 .concat() 1 2 3 4 5 6 7 8 const numbers = [3 , 2 , 1 ]const newFirstNumber = 4 [newFirstNumber].concat (numbers) numbers.concat (newFirstNumber)
如果你想避免改变你的原始数组,你可以使用 concat。
方法 .splice() 1 2 3 4 5 6 7 8 9 10 const months = ['Jan' , 'March' ];months.splice (1 , 0 , 'Feb' ); console .log (months);months.splice (2 , 1 , 'May' ); console .log (months);
方法 .unshift() 1 2 3 4 5 let cats = ['Bob' ];cats.unshift ('Willy' ); cats.unshift ('Puff' , 'George' );
将项目添加到开头 并返回新的数组长度。
方法 .filter() 1 2 3 4 5 6 const words = ['js' , 'java' , 'golang' ];const result = words.filter (word => { return word.length > 3 }); console .log (result);
JavaScript 循环 While 循环 1 2 3 4 5 6 7 8 while (condition) { } let i = 0 ;while (i < 5 ) { console .log (i); i++; }
反向循环 1 2 3 4 5 6 7 const fruits = ["apple" , "dew" , "berry" ];for (let i = fruits.length - 1 ; i >= 0 ; i--) { console .log (`${i} . ${fruits[i]} ` ); }
Do…While 语句 1 2 3 4 5 6 7 8 x = 0 i = 0 do { x = x + i; console .log (x) i++; } while (i < 5 );
For 循环 1 2 3 4 for (let i = 0 ; i < 4 ; i += 1 ) { console .log (i); };
遍历数组 1 2 3 4 for (let i = 0 ; i < array.length ; i++){ console .log (array[i]); }
Break 1 2 3 4 5 for (let i = 0 ; i < 99 ; i += 1 ) { if (i > 5 ) break ; console .log (i) }
Continue 1 2 3 4 5 6 for (i = 0 ; i < 10 ; i++) { if (i === 3 ) { continue ; } text += "The number is " + i + "<br>" ; }
嵌套循环 1 2 3 4 5 for (let i = 0 ; i < 2 ; i += 1 ) { for (let j = 0 ; j < 3 ; j += 1 ) { console .log (`${i} -${j} ` ); } }
for…in 循环 1 2 3 4 5 6 7 const fruits = ["apple" , "orange" , "banana" ];for (let index in fruits) { console .log (index); }
label 语句 1 2 3 4 5 6 7 8 9 10 11 12 13 var num = 0 ;outPoint :for (var i = 0 ; i < 10 ; i++) { for (var j = 0 ; j < 10 ; j++) { if (i == 5 && j == 5 ) { continue outPoint; } num++; } } alert (num);
从 alert(num)
的值可以看出,continue outPoint;
语句的作用是跳出当前循环,并跳转到 outPoint
(标签)下的 for
循环继续执行。
for…of 循环 1 2 3 4 5 6 7 const fruits = ["apple" , "orange" , "banana" ];for (let fruit of fruits) { console .log (fruit); }
for await…of 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 async function * asyncGenerator ( ) { var i = 0 ; while (i < 3 ) { yield i++; } } (async function ( ) { for await (num of asyncGenerator ()) { console .log (num); } })();
可选的 for 表达式 1 2 3 4 5 6 7 var i = 0 ;for (;;) { if (i > 3 ) break ; console .log (i); i++; }
JavaScript 迭代器(Iterators) 分配给变量的函数 1 2 3 4 5 6 7 8 let plusFive = (number ) => { return number + 5 ; }; let f = plusFive;plusFive (3 ); f (9 );
回调函数 1 2 3 4 5 6 7 8 9 10 const isEven = (n ) => { return n % 2 == 0 ; } let printMsg = (evenFunc, num ) => { const isNumEven = evenFunc (num); console .log (`${num} is an even number: ${isNumEven} .` ) } printMsg (isEven, 4 );
数组方法 .reduce() 1 2 3 4 5 const numbers = [1 , 2 , 3 , 4 ];const sum = numbers.reduce ((accumulator, curVal ) => { return accumulator + curVal; }); console .log (sum);
数组方法 .map() 1 2 3 4 5 const members = ["Taylor" , "Donald" , "Don" , "Natasha" , "Bobby" ];const announcements = members.map ((member ) => { return member + " joined the contest." ; }); console .log (announcements);
数组方法 .forEach() 1 2 3 4 const numbers = [28 , 77 , 45 , 99 , 27 ];numbers.forEach (number => { console .log (number); });
数组方法 .filter() 1 2 3 4 const randomNumbers = [4 , 11 , 42 , 14 , 39 ];const filteredArray = randomNumbers.filter (n => { return n > 5 ; });
JavaScript 对象(Objects) 访问属性 1 2 3 4 5 6 const apple = { color : 'Green' , price : { bulk : '$3/kg' , smallQty : '$4/kg' } }; console .log (apple.color ); console .log (apple.price .bulk );
命名属性 1 2 3 4 5 6 7 8 9 const trainSchedule = { platform num : 10 , 40 - 10 + 2 : 30 , +compartment : 'C' }
不存在的属性 1 2 3 4 const classElection = { date : 'January 12' }; console .log (classElection.place );
可变的 1 2 3 4 5 6 7 8 9 10 11 12 13 const student = { name : 'Sheldon' , score : 100 , grade : 'A' , } console .log (student)delete student.score student.grade = 'F' console .log (student)student = {}
赋值简写语法 1 2 3 4 5 6 7 const person = { name : 'Tom' , age : '22' , }; const {name, age} = person;console .log (name); console .log (age);
删除运算符 1 2 3 4 5 6 7 8 9 10 11 12 const person = { firstName : "Matilda" , hobby : "knitting" , goal : "learning JavaScript" }; delete person.hobby ; console .log (person);
对象作为参数 1 2 3 4 5 6 7 8 9 10 11 12 const origNum = 8 ;const origObj = {color : 'blue' };const changeItUp = (num, obj ) => { num = 7 ; obj.color = 'red' ; }; changeItUp (origNum, origObj);console .log (origNum);console .log (origObj.color );
工厂函数 1 2 3 4 5 6 7 8 9 10 11 12 const dogFactory = (name, age, breed ) => { return { name : name, age : age, breed : breed, bark ( ) { console .log ('Woof!' ); } }; };
速记对象创建 1 2 3 const activity = 'Surfing' ;const beach = { activity };console .log (beach);
this 关键字 1 2 3 4 5 6 7 8 const cat = { name : 'Pipey' , age : 8 , whatName ( ) { return this .name } }; console .log (cat.whatName ());
方法 1 2 3 4 5 6 7 8 9 10 11 12 const engine = { start (adverb ) { console .log (`The engine starts up ${adverb} ...` ); }, sputter : () => { console .log ('The engine sputters...' ); }, }; engine.start ('noisily' ); engine.sputter ();
Getters 和 setters 1 2 3 4 5 6 7 8 9 10 11 12 13 const myCat = { _name : 'Dottie' , get name () { return this ._name ; }, set name (newName ) { this ._name = newName; } }; console .log (myCat.name );myCat.name = 'Yankee' ;
Proxy Proxy 对象用于创建一个对象的代理,从而实现基本操作的拦截和自定义(如属性查找、赋值、枚举、函数调用等)。
1 2 3 4 5 6 7 8 9 10 11 12 13 const handler = { get : function (obj, prop ) { return prop in obj ? obj[prop] : 37 ; } }; const p = new Proxy ({}, handler);p.a = 1 ; p.b = undefined ; console .log (p.a , p.b ); console .log ('c' in p, p.c );
语法 1 const 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 2 3 4 5 6 7 8 9 10 11 12 13 const duck = { name : 'Maurice' , color : 'white' , greeting : function ( ) { console .log (`Quaaaack! My name is ${this .name} ` ); } } Reflect .has (duck, 'color' );Reflect .has (duck, 'haircut' );
静态方法
:-
:-
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 绑定 隐式绑定 1 2 3 4 5 6 7 8 9 10 11 12 function foo ( ) { console .log (this ) } let obj1 = { name : "obj1" , foo : foo } let obj2 = { name : "obj2" , obj1 : obj1 } obj2.obj1 .foo ()
隐式丢失 1 2 let a = obj2.obj1 .foo ()a ()
指定隐式绑定:必须在调用的对象内部有一个对函数的引用(比如一个属性)
将以上调用赋值给一个变量,结果最终会是 Window
在 a 被调用的位置没有进行过任何显示绑定,最终全局对象 window 会调用它(Window.a
)
显示绑定 1 2 3 4 5 6 function getName (a1, a2 ) { console .log ("此人" + this .name , "岁数" + (a1 + a2)) } let person = { name : "zhangsan" }
call call 第一个参数接受 this 作用域,剩余参数传递给其调用的函数
1 getName.call (person, 18 , 12 )
apply apply 第一个参数与 call 相同,第二个参数是其调用函数的参数数组
1 getName.apply (person, [18 , 12 ])
bind bind 函数会返回一个新函数
1 2 3 4 5 getName.bind (person,18 ,12 )() getName.bind (person)(18 , 12 ) getName.bind (person).bind (null , 18 )(12 )
内置函数中的 this 数组中的一些方法,类似于 map、forEach 等,可以自己设置绑定 this
1 2 3 4 5 6 7 8 const obj = { name : "zhangsan" } const array = [1 , 2 , 3 ];array.map (function (value ){ console .log (this .name ) }, obj)
其中一些全局对象,如 setTimeout 等,它们和未显示绑定 this 的部分数组方法一样,都会指向全局对象(Window
)
1 2 3 setTimeout (function ( ){ console .log (this ) }, 1000 )
JavaScript Classes 静态方法/字段 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Dog { constructor (name ) { this ._name = name; } introduce ( ) { console .log ('This is ' + this ._name + ' !' ); } static bark ( ) { console .log ('Woof!' ); } static { console .log ('类静态初始化块调用' ); } } const myDog = new Dog ('Buster' );myDog.introduce (); Dog .bark ();
公有静态字段 1 2 3 4 5 6 class ClassStaticField { static staticField = 'static field' } console .log (ClassStaticField .staticField )
Class 1 2 3 4 5 6 7 8 9 10 11 12 13 class Song { constructor ( ) { this .title ; this .author ; } play ( ) { console .log ('Song playing!' ); } } const mySong = new Song ();mySong.play ();
extends 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Media { constructor (info ) { this .publishDate = info.publishDate ; this .name = info.name ; } } class Song extends Media { constructor (songData ) { super (songData); this .artist = songData.artist ; } } const mySong = new Song ({ artist : 'Queen' , name : 'Bohemian Rhapsody' , publishDate : 1975 });
Class Constructor 1 2 3 4 5 6 7 8 class Song { constructor (title, artist ) { this .title = title; this .artist = artist; } } const mySong = new Song ('Bohemian Rhapsody' , 'Queen' );console .log (mySong.title );
Class Methods 1 2 3 4 5 6 7 8 9 class Song { play ( ) { console .log ('Playing!' ); } stop ( ) { console .log ('Stopping!' ); } }
JavaScript Modules Export / Import 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 export default function add (x,y ){ return x + y } export function subtract (x,y ){ return x - y } function multiply (x,y ){ return x * y } function duplicate (x ){ return x * 2 } export { multiply, duplicate }
import 加载模块 1 2 3 4 5 6 7 8 import add, { subtract, multiply, duplicate } from './myMath.js' ;console .log (add (6 , 2 )); console .log (subtract (6 , 2 )) console .log (multiply (6 , 2 )); console .log (duplicate (5 )) <script type="module" src="main.js" ></script>
Export Module 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 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 } module .exports = { add, subtract, multiply, duplicate }
require 加载模块 1 2 3 4 5 6 const myMath = require ('./myMath.js' )console .log (myMath.add (6 , 2 )); console .log (myMath.subtract (6 , 2 )) console .log (myMath.multiply (6 , 2 )); console .log (myMath.duplicate (5 ))
JavaScript Promises Promise 创建 promises
1 2 3 4 5 6 7 new Promise ((resolve, reject ) => { if (ok) { resolve (result) } else { reject (error) } })
使用 promises 1 2 3 promise .then ((result ) => { ··· }) .catch ((error ) => { ··· })
Promise 方法 1 2 3 4 Promise .all (···)Promise .race (···)Promise .reject (···)Promise .resolve (···)
执行器函数 1 2 3 4 const executorFn = (resolve, reject ) => { resolve ('Resolved!' ); }; const promise = new Promise (executorFn);
setTimeout() 1 2 3 4 const loginAlert = ( ) => { console .log ('Login' ); }; setTimeout (loginAlert, 6000 );
Promise 状态 1 2 3 4 5 6 7 8 9 10 11 12 13 14 const promise = new Promise ((resolve, reject ) => { const res = true ; if (res) { resolve ('Resolved!' ); } else { reject (Error ('Error' )); } }); promise.then ( (res ) => console .log (res), (err ) => console .error (err) );
.then() 方法 1 2 3 4 5 6 7 8 9 10 11 const promise = new Promise ((resolve, reject ) => { setTimeout (() => { resolve ('Result' ); }, 200 ); }); promise.then ((res ) => { console .log (res); }, (err ) => { console .error (err); });
.catch() 方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 const promise = new Promise ( (resolve, reject ) => { setTimeout (() => { reject (Error ('Promise 无条件拒绝。' )); }, 1000 ); }); promise.then ((res ) => { console .log (value); }); promise.catch ((err ) => { console .error (err); });
Promise.all() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 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 ]); });
链接多个 .then() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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 和 .then() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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); }; promise.then (twoStars).then (oneDot).then (print);
JavaScript Async-Await 异步 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 function helloWorld ( ) { return new Promise (resolve => { setTimeout (() => { resolve ('Hello World!' ); }, 2000 ); }); } const msg = async function ( ) { const msg = await helloWorld (); console .log ('Message:' , msg); } const msg1 = async ( ) => { const msg = await helloWorld (); console .log ('Message:' , msg); } msg (); msg1 ();
解决 Promises 1 2 3 4 5 6 7 8 9 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); });
异步等待 Promises 1 2 3 4 5 6 7 8 9 10 11 12 function helloWorld ( ) { return new Promise (resolve => { setTimeout (() => { resolve ('Hello World!' ); }, 2000 ); }); } async function msg ( ) { const msg = await helloWorld (); console .log ('Message:' , msg); } msg ();
错误处理 1 2 3 4 5 6 7 8 9 let json = '{ "age": 30 }' ;try { let user = JSON .parse (json); console .log ( user.name ); } catch (e) { console .error ( "Invalid JSON data!" ); }
异步等待运算符 1 2 3 4 5 6 7 8 9 10 11 12 function helloWorld ( ) { return new Promise (resolve => { setTimeout (() => { resolve ('Hello World!' ); }, 2000 ); }); } async function msg ( ) { const msg = await helloWorld (); console .log ('Message:' , msg); } msg ();
JavaScript 请求 JSON 1 2 3 4 5 const jsonObj = { "name" : "Rick" , "id" : "11A" , "level" : 4 };
另见:JSON 备忘单
XMLHttpRequest 1 2 const xhr = new XMLHttpRequest ();xhr.open ('GET' , 'mysite.com/getjson' );
XMLHttpRequest
是一个浏览器级别的 API,它使客户端能够通过 JavaScript 编写数据传输脚本,而不是 JavaScript 语言的一部分。
GET 1 2 3 4 5 6 7 const req = new XMLHttpRequest ();req.responseType = 'json' ; req.open ('GET' , '/getdata?id=65' ); req.onload = () => { console .log (xhr.response ); }; req.send ();
POST 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 const data = { weight : '1.5 KG' };const xhr = new XMLHttpRequest ();xhr.open ('POST' , '/inventory/add' ); xhr.responseType = 'json' ; xhr.send (JSON .stringify (data)); xhr.onload = () => { console .log (xhr.response ); } xhr.onerror = () => { console .log (xhr.response ); }
fetch api 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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 格式 1 2 3 4 5 fetch ('url-that-returns-JSON' ) .then (response => response.json ()) .then (jsonResponse => { console .log (jsonResponse); });
promise url 参数获取 API 1 2 3 4 5 6 fetch ('url' ) .then (response => { console .log (response); }, rejection => { console .error (rejection.message ); });
Fetch API 函数 1 2 3 4 5 6 7 8 9 10 11 12 13 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 语法 1 2 3 4 5 6 7 8 9 10 11 12 13 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) } }