String Skill
:字符串技巧Number Skill
:數值技巧Boolean Skill
:布爾技巧Array Skill
:數組技巧Object Skill
:對象技巧Function Skill
:函數技巧DOM Skill
:DOM技巧《ES6標準入門》web
時間個位數形式需補0數組
const time1 = "2019-02-14 21:00:00";
const time2 = "2019-05-01 09:00:00";
const overtime = time1 > time2;
// overtime => false
複製代碼
const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const money = ThousandNum(20190214);
// money => "20,190,214"
複製代碼
const RandomId = len => Math.random().toString(36).substr(3, len);
const id = RandomId(10);
// id => "jg7zpgiqva"
複製代碼
const RandomColor = () => "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0");
const color = RandomColor();
// color => "#f03665"
複製代碼
const StartScore = rate => "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
const start = StartScore(3);
// start => "★★★"
複製代碼
const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?name=young&sex=male"
params.has("young"); // true
params.get("sex"); // "male"
複製代碼
代替正數的
Math.floor()
,代替負數的Math.ceil()
promise
const num1 = ~~ 1.69;
const num2 = 1.69 | 0;
const num3 = 1.69 >> 0;
// num1 num2 num3 => 1 1 1
複製代碼
const FillZero = (num, len) => num.toString().padStart(len, "0");
const num = FillZero(169, 5);
// num => "00169"
複製代碼
只對null、""、false、數值字符串有效markdown
const num1 = +null;
const num2 = +"";
const num3 = +false;
const num4 = +"169";
// num1 num2 num3 num4 => 0 0 0 169
複製代碼
const timestamp = +new Date("2019-02-14");
// timestamp => 1550102400000
複製代碼
const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;
const num = RoundNum(1.69, 1);
// num => 1.7
複製代碼
const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;
const num = RoundNum(1.69, 1);
// num => 1.7
複製代碼
const arr = [0, 1, 2];
const min = Math.min(...arr);
const max = Math.max(...arr);
// min max => 0 2
複製代碼
const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const num = RandomNum(1, 10);
複製代碼
const a = d && 1; // 知足條件賦值:取假運算,從左到右依次判斷,遇到假值返回假值,後面再也不執行,不然返回最後一個真值
const b = d || 1; // 默認賦值:取真運算,從左到右依次判斷,遇到真值返回真值,後面再也不執行,不然返回最後一個假值
const c = !d; // 取假賦值:單個表達式轉換爲true則返回false,不然返回true
複製代碼
可判斷類型:undefined、null、string、number、boolean、array、object、symbol、date、regexp、function、asyncfunction、arguments、set、map、weakset、weakmap
複製代碼
function DataType(tgt, type) {
const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1").toLowerCase();
return type ? dataType === type : dataType;
}
DataType("young"); // "string"
DataType(20190214); // "number"
DataType(true); // "boolean"
DataType([], "array"); // true
DataType({}, "array"); // false
複製代碼
const arr = [];
const flag = Array.isArray(arr) && !arr.length;
// flag => true
複製代碼
const obj = {};
const flag = DataType(obj, "object") && !Object.keys(obj).length;
// flag => true
複製代碼
const flagA = true; // 條件A
const flagB = false; // 條件B
(flagA || flagB) && Func(); // 知足A或B時執行
(flagA || !flagB) && Func(); // 知足A或不知足B時執行
flagA && flagB && Func(); // 同時知足A和B時執行
flagA && !flagB && Func(); // 知足A且不知足B時執行
複製代碼
const flag = false; // undefined、null、""、0、false、NaN
!flag && Func();
複製代碼
const arr = [0, 1, 2];
arr.length && Func();
複製代碼
const obj = { a: 0, b: 1, c: 2 };
Object.keys(obj).length && Func();
複製代碼
if (flag) {
Func();
return false;
}
// 換成
if (flag) {
return Func();
}
複製代碼
const age = 26;
switch (true) {
case isNaN(age):
console.log("not a number");
break;
case (age < 18):
console.log("under age");
break;
case (age >= 18):
console.log("adult");
break;
default:
console.log("please set your age");
break;
}
複製代碼
const _arr = [0, 1, 2];
const arr = [..._arr];
// arr => [0, 1, 2]
複製代碼
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
const arr = [...arr1, ...arr2];
// arr => [0, 1, 2, 3, 4, 5];
複製代碼
const arr = [...new Set([0, 1, 1, null, null])];
// arr => [0, 1, null]
複製代碼
const arr = [0, 1, 2, 3, 4, 5].slice().sort(() => Math.random() - .5);
// arr => [3, 4, 0, 5, 1, 2]
複製代碼
const arr = [0, 1, 2];
arr.length = 0;
// arr => []
複製代碼
const arr = [0, 1, 2]
arr.length = 2;
// arr => [0, 1]
複製代碼
let a = 0;
let b = 1;
[a, b] = [b, a];
// ab => 1 0
複製代碼
空值: undefined、null、""、0、false、NaNdom
const arr = [undefined, null, "", 0, false, NaN, 1, 2].filter(Boolean);
// arr => [1, 2]
複製代碼
async function Func(deps) {
return deps.reduce(async(t, v) => {
const dep = await t;
const version = await Todo(v);
dep[v] = version;
return dep
}, Promise.resolve({}));
}
const result = await Func(); // 須要async 包圍下使用
複製代碼
let arr = [1, 2]; // 如下方法任選一種
arr.unshift(0);
arr = [0].concat(arr);
arr = [0,...arr];
// arr => [0, 1, 2]
複製代碼
let arr = [0, 1]; // 如下方法任選一種
arr.push(2);
arr.concat(2);
arr[arr.length] = 2;
arr = [...arr, 2];
// arr => [0, 1, 2]
複製代碼
const arr = [0, 1, 1, 2, 2, 2];
const count = arr.reduce((t, v) => {
t[v] = t[v] ? ++[v] : 1;
return t;
},{});
// count => { 0: 1, 1: 2, 2: 3 }
複製代碼
const arr = [0, 1, [2, 3, [4, 5]]];
const [a, b, [c, d, [e, f]]] = arr;
// a b c d e f => 0 1 2 3 4 5
複製代碼
const arr = [0, 1, 2];
const { 0: a, 1: b, 2: c } = arr
// a b c => 0 1 2
複製代碼
const arr = [0, 1, 2];
const [a, b, c = 3, d = 4] = arr;
// a b c d => 0 1 2 4
複製代碼
const arr = [1, 2, 3, 4, 5];
const randomItem = arr[Math.floor(Math.random() * arr.length)];
// randomItem => 1
複製代碼
const arr = [...new Array(3).keys()];
// arr => [0, 1, 2]
複製代碼
const arr = new Array(3).fill(0);
// arr => [0, 0, 0]
複製代碼
const _arr = [0, 1, 2];
// map
const arr = _arr.map(v => v * 2);
const arr = _arr.reduce((t, v) => {
t.push(v * 2);
return t;
}, []);
// arr => [0, 2, 4]
// filter
const arr = _arr.filter(v => v > 0);
const arr = _arr.reduce((t, v) => {
v > 0 && t.push(v);
return t;
}, []);
// arr => [1, 2]
// map 和 filter
const arr = _arr.map(v => v * 2).filter(v => v > 2);
const arr = _arr.reduce((t, v) => {
v = v * 2;
v > 2 && t.push(v);
return t;
}, []);
// arr => [4]
複製代碼
const _obj = { a: 0, b: 1, c: 2 };
const obj = { ..._obj };
const obj = JSON.parse(JSON.stringify(_obj));
// obj => { a: 0, b: 1, c: 2 }
複製代碼
const obj1 = { a: 0, b: 1, c: 2 };
const obj2 = { c: 3, d: 4, e: 5 };
const obj = { ...obj1, ...obj2 };
// obj => { a: 0, b: 1, c: 3, d: 4, e: 5 }
複製代碼
獲取環境變量時必用此方法,用它一直爽,一直用它一直爽異步
const env = "prod";
const link = {
dev: "Development Address",
test: "Testing Address",
prod: "Production Address"
}[env];
// link => "Production Address"
複製代碼
const flag = false;
const obj = {
a: 0,
b: 1,
[flag ? "c" : "d"]: 2
};
// obj => { a: 0, b: 1, d: 2 }
複製代碼
const obj = Object.create(null);
Object.prototype.a = 0;
// obj => {}
複製代碼
const obj = { a: 0, b: 1, c: 2 }; // 只想拿b和c
const { a, ...rest } = obj;
// rest => { b: 1, c: 2 }
複製代碼
const obj = { a: 0, b: 1, c: { d: 2, e: 3 } };
const { c: { d, e } } = obj;
// d e => 2 3
複製代碼
const obj = { a: 0, b: 1, c: 2 };
const { a, b: d, c: e } = obj;
// a d e => 0 1 2
複製代碼
const obj = { a: 0, b: 1, c: 2 };
const { a, b = 2, d = 3} = obj;
// a b d => 0 1 3
複製代碼
const Func = function() {}(); // 經常使用
(function() {})(); // 經常使用
(function() {}()); // 經常使用
[function() {}()];
+ function() {}();
- function() {}();
~ function() {}();
! function() {}();
new function() {};
new function() {}();
void function() {}();
typeof function() {}();
delete function() {}();
1, function() {}();
1 ^ function() {}();
1 > function() {}();
複製代碼
只能用於
單語句返回值箭頭函數
,若是返回值是對象必須使用()包住async
const Func = function(name) {
return "I Love " + name
}
// 換成
const Func = name => "I Love " + name;
複製代碼
適用於運行一些只須要執行一次的初始化代碼函數
function Func() {
console.log("x")
Func = function() {
console.log("y")
}
}
複製代碼
函數內判斷分支較多較複雜時能夠大大節約資源開銷oop
function Func() {
if (a === b){
console.log("x");
}else {
console.log("Y");
}
}
// 換成
function Func() {
if(a === b) {
Func = function() {
console.log("x")
}
}else {
Func = function() {
console.log("y")
}
}
return Func();
}
複製代碼
function IsRequired() {
throw new Error("param is required");
}
function Func(name = IsRequired()) {
console.log("I Love" + name)
}
Func(); // "param is required"
Func("You") // "I Love You"
複製代碼
const Func = new Function("name", "console.log(\"I Love \" + name)");
複製代碼
try {
Func();
} catch (e) {
location.href = "https://stackoverflow.com/search?q=[js]+" + e.message;
}
複製代碼
function AsyncTo(promise) {
return promise.then(data => [null, data]).catch(err => [err]);
}
const [err, res] = await AsyncTo(Func());
複製代碼
function Func() {
return Promise.all([
fetch("/user"),
fetch("/comment")
])
}
const [user, comment] = await Func(); // 需在async 包圍下使用
複製代碼
調試頁面元素邊界時使用
[].forEach.call($$("*"), dom => {
dom.style.outline = "1px solid #" + (~~(Math.random() * (1 << 24))).toString(16);
});
複製代碼
頁面基於一張設計圖但須要作多款機型自適應,元素尺寸使用rem進行設置
function AutoResponse(width = 750) {
const target = document.documentElement;
target.clientWidth >= 600
? (target.style.fontSize = "80px")
: (target.style.fontSize = target.clientWidth / width * 100 + "px");
}
複製代碼
function FilterXss(content) {
let elem = document.createElement("div");
elem.innerText = content;
const result = elem.innerHTML;
elem = null;
return result;
}
複製代碼
反序列化取, 序列化存
localStorage.setItem("love", JSON.stringify("I Love You"));
const love = JSON.parse(localStorage.getItem("love"));
複製代碼
鍵盤
(_=>[..."`1234567890-=~~QWERTYUIOP[]\\~ASDFGHJKL;'~~ZXCVBNM,./~"].map(x=>(o+=`/${b='_'.repeat(w=x<y?2:' 667699'[x=["Bs","Tab","Caps","Enter"][p++]||'Shift',p])}\\|`,m+=y+(x+' ').slice(0,w)+y+y,n+=y+b+y+y,l+=' __'+b)[73]&&(k.push(l,m,n,o),l='',m=n=o=y),m=n=o=y='|',p=l=k=[])&&k.join` `)()
複製代碼