JS缩写
//函式缩写const obj = { myName: "obj", fn: function () { //可缩写为fn() {...} return this.myName; },};//物件this缩写const name = "小明";function fn() { return this.name;}const person = { name: name, // 可缩为只写name fn: fn, // fn};//展开式const groupA = [1, 2, 3];const groupB = [4, 5, 6];const groupC = groupA.concat(groupB); // 可改为 groupC = [...groupA, ...groupB]//物件中的展开式const method = { fn1() { console.log(1); }, fn2() { console.log(2); },};// const newMethod = method;// newMethod.fn3 = function () {// console.log(3);// };// console.log(method); //多了fn3物件 与预期不符const newMethod = { ...method, fn3() { console.log(3); },};console.log(method); //原物件正常,不会出现fn3//以展开式将非纯阵列转为纯阵列 即可使用阵列方法map等const doms = document.querySelectorAll("li");console.log(doms); //Nodelist(5)const newDoms = [...doms];console.log(newDoms); //[li, li, li, li, li]//参数预设值function sum(a, b = 1) { return a + b;}console.log(sum(1)); // 2console.log(sum(1, 2)); // 3
解构
const person = { name: "小明", age: 16, like: "泡麵",};// const name = person.name// const age = person.age// 可写成;const { name, age, like } = person;console.log(name, age, like); //小明 16 泡麵const person = { Ming: { name: "小明", age: 16, like: "泡麵", }, Aunt: { name: "阿丽", age: 52, like: "白饭", }, Uncle: { name: "阿叔", age: 55, like: "厨余", },};const { Ming, ...other } = person; //other可自行命名console.log(Ming);console.log(other); // {{Aunt}, {Uncle}}
let Ming = {};const { Ming: willy } = person; //等同 const willy = person.Mingconsole.log(willy); //呈现以下// Ming: {// name: "小明",// age: 16,// like: "泡麵",// }const person = { name: "Ming", age: 16, like: "白饭",};function callName({ name, age }) { console.log(name, age);}callName(person); // Ming 16
箭头函式arrow function
function fn(a, b) { return a * b;}//可改写为const fn = (a, b) => a * b;//单一参数去括号const a = (num) => num * 5; //参数只有一个 可改为const a = num => num * 5;console.log(a(5));const fn = () => ({ //物件须加上小括号 name: "Ming",});箭头函式的this 都是跟着上一层
阵列操作
const people = [ { name: "Adam", like: "a", price: 1, }, { name: "Bob", like: "b", price: 2, }, { name: "Candy", like: "c", price: 3, },];//forEach操作原本阵列的值 除非是要修改全部资料 不然动到原阵列容易产生bugpeople.forEach((item) => { item.price = item.price * 0.8;});//map产生新阵列,不影响原本阵列的值const newOrder = people.map((i) => { return { price: i.price * 0.8, like: i.like, name: i.name, };});//map可删去return 若为物件须加上小括号const newOrder = people.map((i) => ({ price: i.price * 0.8, like: i.like, name: i.name,}));//判断时用filter//!!注意错误用法const filterOrder = people.filter((i) => { i.price > 1;});//filter不能加大括号return值(因不回传值)//须改为const filterOrder = people.filter((i) => i.price > 1);console.log(filterOrder); //[people[0], people[1]] //为省空间进行缩写
物件传参考
const person = { name: "Ming", obj: {},};const person2 = person;person2.name = "Jay";console.log(person.name); //原物件name被变更为Jayconst { obj } = person; //等同obj = person.objobj.name = "person下的物件";console.log(person.obj.name); //person下的物件console.log(person2.obj.name); //person下的物件//深层拷贝const person = { name: "Ming", obj: {},};//转成字串再转成物件(从内stringify开始运作)const person2 = JSON.parse(JSON.stringify(person));console.log(person2); //变回物件person2.name = "Jay";console.log(person.name); //Mingconsole.log(person2.name); //Jayperson2.obj.name = "Jay~";console.log(person.obj.name); //undefined
Promise串接
const promiseSetTimeOut = (status) => { return new Promise((resolve, reject) => { setTimeout(() => { if (status) { resolve("success"); } else { reject("fail"); } }, 0); });};// 1 suc 2 suc 3 串接console.log(1);promiseSetTimeOut(1) .then((res) => { console.log(res); console.log(2); return promiseSetTimeOut(1); }) .then((res) => { console.log(res); console.log(3); });//实战一般使用axios(promise函式库)来写axios .get("https://randomuser.me/api1/") .then((res) => { console.log(res); }) .catch((err) => { console.log(err); });
async function(记得加上await)
(async () => { const res = await axios.get("https://randomuser.me/api/"); const { seed } = res.data.info; //使下次能取到同样的使用者资料 console.log(res); const res2 = await axios.get(`https://randomuser.me/api/?seed=${seed}`); console.log(res2);})();//含捕捉错误的写法 (try catch throw)const asyncFn = async () => { try { const res = await axios.get("https://jsonplaceholder.typicode.com/todos/1"); return res; } catch (error) { throw error; //使用throw 而非return }};asyncFn() .then((res) => { console.log("promise:", res); }) .catch((error) => { console.log("promise error:", error); });
模组化ESModule
//预设汇出export default (常用)//appp.js中export default function fn() { console.log(1);}//index.html中将type="text/babel"改为 type="module"(因两者会冲突)https://stackoverflow.com/questions/54018182/how-to-make-script-type-both-text-babel-and-module此篇有并存的教学 import fn from "./appp.js"; fn(); //1 //具名汇出 (汇出方法用)//appp.jsexport const a = 5;export function fa() { console.log(2);}//index.html import { fa } from "./appp.js"; fa(); //2 import { a } from "./appp.js"; console.log(a + a); //10