编程·
JavaScript速查表
一个包含JavaScript中最重要的概念、函数、方法等内容的速查表。适合初学者快速参考。
入门
简介
JavaScript 是一种轻量级的、解释性的编程语言。
- JSON 速查表 (chatsheet.org)
- JavaScript 中的正则表达式 (chatsheet.org)
控制台
// => Hello world!
console.log("Hello world!");
// => Hello chatsheet.org
console.warn("hello %s", "chatsheet.org");
// Prints error message to stderr
console.error(new Error("Oops!"));
数字
let amount = 6;
let price = 4.99;
变量
let x = null;
let name = "Tammy";
const found = false;
// => Tammy, false, null
console.log(name, found, x);
var a;
console.log(a); // => undefined
字符串
let single = "Wheres my bandit hat?";
let double = "Wheres my bandit hat?";
// => 21
console.log(single.length);
算术运算符
5 + 5 = 10 // Addition
10 - 5 = 5 // Subtraction
5 * 10 = 50 // Multiplication
10 / 5 = 2 // Division
10 % 5 = 0 // Modulo
注释
// This line will denote a comment
/*
The below configuration must be
changed before deployment.
*/
赋值运算符
let number = 100;
// Both statements will add 10
number = number + 10;
number += 10;
console.log(number);
// => 120
字符串插值
let age = 7;
// String concatenation
"Tommy is " + age + " years old.";
// String interpolation
`Tommy is ${age} years old.`;
let 关键字
let count;
console.log(count); // => undefined
count = 10;
console.log(count); // => 10
const 关键字
const numberOfColumns = 4;
// TypeError: Assignment to constant...
numberOfColumns = 8;
JavaScript 条件语句
if 语句
const isMailSent = true;
if (isMailSent) {
console.log("Mail sent to recipient");
}
三元运算符
var x = 1;
// => true
result = x == 1 ? true : false;
逻辑运算符
true || false; // true
10 > 5 || 10 > 20; // true
false || false; // false
10 > 100 || 10 > 20; // false
逻辑运算符 &&
true && true; // true
1 > 2 && 2 > 1; // false
true && false; // false
4 === 4 && 3 > 1; // true
比较运算符
1 > 3; // false
3 > 1; // true
250 >= 250; // true
1 === 1; // true
1 === 2; // false
1 === "1"; // false
逻辑运算符 !
let lateToWork = true;
let oppositeValue = !lateToWork;
// => false
console.log(oppositeValue);
空值合并运算符 ??
null ?? "I win"; // 'I win'
undefined ?? "Me too"; // 'Me too'
false ?? "I lose"; // false
0 ?? "I lose again"; // 0
"" ?? "Damn it"; // ''
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 语句
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");
}
== vs ===
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
== 只检查值,=== 同时检查值和类型。
JavaScript 函数
函数
// Defining the function:
function sum(num1, num2) {
return num1 + num2;
}
// Calling the function:
sum(3, 6); // 9
匿名函数
// Named function
function rocketToMars() {
return "BOOM!";
}
// Anonymous function
const rocketToMars = function () {
return "BOOM!";
};
箭头函数(ES6)
有两个参数
const sum = (param1, param2) => {
return param1 + param2;
};
console.log(sum(2, 5)); // => 7
没有参数
const printHello = () => {
console.log("hello");
};
printHello(); // => hello
一个参数
const checkWeight = (weight) => {
console.log(`Weight : ${weight}`);
};
checkWeight(25); // => Weight : 25
简洁的箭头函数
const multiply = (a, b) => a * b;
// => 60
console.log(multiply(2, 30));
箭头函数 从 ES2015 开始可用。
return 关键字
// With return
function sum(num1, num2) {
return num1 + num2;
}
// The function doesn't output the sum
function sum(num1, num2) {
num1 + num2;
}
调用函数
// Defining the function
function sum(num1, num2) {
return num1 + num2;
}
// Calling the function
sum(2, 4); // 6
函数表达式
const dog = function () {
return "Woof!";
};
函数参数
// The parameter is name
function sayHello(name) {
return `Hello, ${name}!`;
}
函数声明
function add(num1, num2) {
return num1 + num2;
}
JavaScript 作用域
作用域
function myFunction() {
var pizzaName = "Margarita";
// 此处的代码可以使用pizzaName
}
// 此处的代码不能使用pizzaName
块级作用域变量
const isLoggedIn = true;
if (isLoggedIn == true) {
const statusMessage = "Logged in.";
}
// Uncaught ReferenceError...
console.log(statusMessage);
Global Variables
// 未捕获的引用错误...
const color = "blue";
function printColor() {
console.log(color);
}
printColor(); // => blue
let vs var
for (let i = 0; i < 3; i++) {
// 这是'let'的最大作用域
// i可访问 ✔️
}
// i不可访问 ❌
var
变量的作用域限定在最近的函数块内,而 let
变量的作用域限定在最近的封闭块内。
闭包中的循环
// 打印三个3,这不是我们想要的
for (var i = 0; i < 3; i++) {
setTimeout((_) => console.log(i), 10);
}
// 按预期打印0、1和2
for (let j = 0; j < 3; j++) {
setTimeout((_) => console.log(j), 10);
}
使用 let
声明的变量有自己的副本,而使用 var
声明的变量则是共享的。
JavaScript 数组
数组
const fruits = ["apple", "orange", "banana"];
// 不同的数据类型
const data = [1, "chicken", false];
属性 .length
const numbers = [1, 2, 3, 4];
numbers.length; // 4
索引
// 访问数组元素
const myArray = [100, 200, 300];
console.log(myArray[0]); // 100
console.log(myArray[1]); // 200
增删改
新增 | 删除 | 开始 | 结束 | |
---|---|---|---|---|
push | ✔ | ✔ | ||
pop | ✔ | ✔ | ||
unshift | ✔ | ✔ | ||
shift | ✔ | ✔ |
Array.push()
// 添加单个元素:
const cart = ["apple", "orange"];
cart.push("pear");
// 添加多个元素:
const numbers = [1, 2];
numbers.push(3, 4, 5);
向数组末尾添加元素并返回新的数组长度。
Array.pop()
const fruits = ["apple", "orange", "banana"];
const fruit = fruits.pop(); // 'banana'
console.log(fruits); // ["apple", "orange"]
从数组末尾移除一个元素并返回被移除的元素。
Array.shift()
let cats = ["Bob", "Willy", "Mini"];
cats.shift(); // ['Willy', 'Mini']
从数组开头移除一个元素并返回被移除的元素。
Array.unshift()
let cats = ["Bob"];
// => ['Willy', 'Bob']
cats.unshift("Willy");
// => ['Puff', 'George', 'Willy', 'Bob']
cats.unshift("Puff", "George");
在数组开头添加项目,并返回新数组的长度。
Array.concat()
const numbers = [3, 2, 1];
const newFirstNumber = 4;
// => [ 4, 3, 2, 1 ]
[newFirstNumber].concat(numbers);
// => [ 3, 2, 1, 4 ]
numbers.concat(newFirstNumber);
如果你想避免改变原始数组,你可以使用 concat
函数。
JavaScript Set
创建 Set
// 空的 Set 对象
const emptySet = new Set();
// 包含值的 Set 对象
const setObj = new Set([1, true, "hi"]);
添加
const emptySet = new Set();
// 添加值
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"]);
// 删除值
emptySet.delete("a"); // 1, true
emptySet.delete(true); // 1
emptySet.delete(1); //
Has 方法
const setObj = new Set([1, true, "a"]);
// 返回 true or false
setObj.has("a"); // true
setObj.has(1); // true
setObj.has(false); // false
Clear 方法
const setObj = new Set([1, true, "a"]);
// 清空set
console.log(setObj); // 1, true, 'a'
setObj.clear(); //
Size 属性
const setObj = new Set([1, true, "a"]);
console.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 (条件) {
// 要执行的代码块
}
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
遍历数组
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
// 输出数组中的每个项目
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>";
}
嵌套循环
for (let i = 0; i < 2; i += 1) {
for (let j = 0; j < 3; j += 1) {
console.log(`${i}-${j}`);
}
}
for...in 循环
const fruits = ["apple", "orange", "banana"];
for (let index in fruits) {
console.log(index);
}
// => 0
// => 1
// => 2
for...of 循环
const fruits = ["apple", "orange", "banana"];
for (let fruit of fruits) {
console.log(fruit);
}
// => apple
// => orange
// => banana
JavaScript 迭代器
赋值给变量的函数
let plusFive = (number) => {
return number + 5; // 返回传入数字加5的结果
};
// 将 plusFive 函数赋值给变量 f
let f = plusFive;
plusFive(3); // 输出 8
// 由于 f 变量存储了函数的引用,它可以被调用。
f(9); // 输出 14
回调函数
const isEven = (n) => {
return n % 2 === 0; // 判断 n 是否为偶数
};
const printMsg = (evenFunc, num) => {
const isNumEven = evenFunc(num); // 使用 evenFunc 函数判断 num 是否为偶数
console.log(`${num} 是否为偶数: ${isNumEven}。`); // 打印结果
};
// 将 isEven 函数作为回调函数传入 printMsg
printMsg(isEven, 4);
// 输出: 4 是否为偶数: True。
reduce 方法
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, curVal) => {
return accumulator + curVal;
});
console.log(sum); // 10
map 方法
const members = ["Taylor", "Donald", "Don", "Natasha", "Bobby"];
const announcements = members.map((member) => {
return member + " joined the contest.";
});
console.log(announcements);
forEach 方法
const numbers = [28, 77, 45, 99, 27];
numbers.forEach((number) => {
console.log(number);
});
filter 方法
const randomNumbers = [4, 11, 42, 14, 39];
const filteredArray = randomNumbers.filter((n) => {
return n > 5;
});
JavaScript 对象
访问属性
const apple = {
color: "Green",
price: { bulk: "$3/kg", smallQty: "$4/kg" },
};
console.log(apple.color); // => Green
console.log(apple.price.bulk); // => $3/kg
命名属性
// 无效的键名示例
const trainSchedule = {
// 由于单词之间有空白,所以无效。属性名不能包含空格。
platform num: 10,
// 表达式不能作为键。属性名必须是合法的标识符。
40 - 10 + 2: 30,
// '+' 符号无效,除非它被引号包围。属性名中的特殊字符需要用引号括起来。
+compartment: 'C'
}
不存在的属性
const classElection = {
date: "January 12",
};
// 尝试访问不存在的属性 place
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 属性
delete student.score;
// 修改 student 对象的 grade 属性为 "F"
student.grade = "F";
console.log(student);
// 输出: { name: 'Sheldon', grade: 'F' }
// 尝试重新赋值 student 为一个空对象
// TypeError: Assignment to constant variable.
student = {};
赋值语句的简写语法
const person = {
name: "Tom",
age: "22",
};
// 使用解构赋值,从 person 对象中提取 name 和 age 属性
const { name, age } = person;
console.log(name); // 输出 'Tom'
console.log(age); // 输出 '22'
删除操作符
const person = {
firstName: "Matilda",
age: 27,
hobby: "knitting",
goal: "learning JavaScript",
};
// 使用 delete 操作符删除 person 对象的 hobby 属性
delete person.hobby; // 或者使用 delete person['hobby'];
console.log(person);
/*
输出结果将不包含 hobby 属性:
{
firstName: "Matilda",
age: 27,
goal: "learning JavaScript"
}
*/
对象作为参数
const origNum = 8;
const origObj = { color: "blue" };
const changeItUp = (num, obj) => {
num = 7; // num 是原始值的拷贝,修改它不会影响到origNum
obj.color = "red"; // obj 是原始对象的引用,修改它会影响到origObj
};
changeItUp(origNum, origObj);
// 将输出 8,因为整数是通过值传递的。
console.log(origNum);
// 将输出 'red',因为对象是通过引用传递的,因此是可变的。
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
工厂函数
// 一个工厂函数,它接受 'name'(名字)、'age'(年龄)和 'breed'(品种)参数
// 并返回一个定制的狗对象。
const dogFactory = (name, age, breed) => {
return {
name: name,
age: age,
breed: breed,
bark() {
console.log("Woof!");
},
};
};
对象方法
const engine = {
// 方法简写,带有一个参数
start(adverb) {
console.log(`The engine starts up ${adverb}...`);
},
// 匿名箭头函数表达式,不带参数
sputter: () => {
console.log("The engine sputters...");
},
};
engine.start("noisily");
engine.sputter();
获取器和设置器
const myCat = {
_name: "Dottie",
get name() {
return this._name;
},
set name(newName) {
this._name = newName;
},
};
// 引用获取器
console.log(myCat.name);
// 赋值调用设置器
myCat.name = "Yankee";
JavaScript 中的类
静态方法
class Dog {
constructor(name) {
this._name = name;
}
introduce() {
console.log("This is " + this._name + " !");
}
// 静态方法
static bark() {
console.log("Woof!");
}
}
const myDog = new Dog("Buster");
myDog.introduce();
// 调用静态方法bark
Dog.bark();
Class 类
class Song {
constructor() {
this.title;
this.author;
}
play() {
console.log("Song playing!");
}
}
const mySong = new Song();
mySong.play();
构造函数
class Song {
constructor(title, artist) {
this.title = title;
this.artist = artist;
}
}
const mySong = new Song("Bohemian Rhapsody", "Queen");
console.log(mySong.title);
类方法
class Song {
play() {
console.log("Playing!");
}
stop() {
console.log("Stopping!");
}
}
extends 关键字
// 父类
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,
});
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,
};
Require Module
// 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 Promises
Promise states
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 function
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 被无条件地拒绝了"));
}, 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 和 .then()
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);
创建
const executorFn = (resolve, reject) => {
console.log("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 () {
//异步函数表达式
const msg = await helloWorld();
console.log("Message:", msg);
};
const msg1 = async () => {
//异步箭头函数
const msg = await helloWorld();
console.log("Message:", msg);
};
msg(); // 两秒后控制台输出 "Message: Hello World!"
msg1(); // 两秒后控制台输出 "Message: Hello World!"
Promise 的 resolve 函数
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);
});
// 预期输出 => 数组 [5, 44, "foo"]
Async、Await 和 Promises
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!"
错误处理
let json = '{ "age": 30 }'; // 数据不完整
try {
let user = JSON.parse(json); // <-- 没有错误
console.log(user.name); // 没有name属性!
} catch (e) {
console.error("无效的JSON数据!");
}
async 和 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!"
JavaScript 请求
JSON
const jsonObj = {
"name": "Rick",
"id": "11A",
"level": 4
};
Also see: JSON 速查表
XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open("GET", "mysite.com/getjson");
XMLHttpRequest
是一个浏览器级别的 API,它允许客户端通过 JavaScript 脚本化数据传输,不是 JavaScript 语言的一部分。
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 接口
fetch(url, {
// 这里的 `url` 应该替换为实际的请求地址
method: "POST", // 请求方法
headers: {
"Content-Type": "application/json", // 设置内容类型为JSON
apikey: apiKey, // 假设 `apiKey` 是你的API密钥变量
},
body: JSON.stringify(data), // 将JavaScript对象转换为JSON字符串,`data` 是要发送的数据
}).then(
(response) => {
if (response.ok) {
return response.json(); // 如果响应状态是成功的,将响应体解析为JSON
}
throw new Error("请求失败!"); // 如果响应状态不是成功的,抛出错误
},
(networkError) => {
console.log(networkError.message); // 打印网络错误信息
}
);
JSON 格式化
fetch("返回JSON的URL") // 将 "返回JSON的URL" 替换为实际返回JSON数据的URL
.then((response) => response.json()) // 将响应体(Response)转换为JSON格式
.then((jsonResponse) => {
console.log(jsonResponse); // 打印解析后的JSON响应数据
});
Promise URL 参数 fetch API
fetch("url") // 这里的 'url' 应该替换为实际的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("请求失败!");
},
(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);
}
};