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)); // 2
console.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.Ming
console.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操作原本陣列的值 除非是要修改全部資料 不然動到原陣列容易產生bug
people.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被變更為Jay
const { obj } = person; //等同obj = person.obj
obj.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); //Ming
console.log(person2.name); //Jay
person2.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.js
export 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