用得上的JavaScript 代碼片段和技巧

過去陸陸續(xù)續(xù)總結(jié)了一些有助項(xiàng)目開發(fā)效率和開發(fā)技能的代碼片段,一方面加深對 Javascript 語法的理解,一方面對代碼進(jìn)行歸檔。本文總結(jié)一些項(xiàng)目開發(fā)中用得上的使用方法及代碼整潔的技巧。
實(shí)用方法
1. localStorage
localStorage 是HTML5中的本地持久化存儲方法之一,也是前端項(xiàng)目常用的本地存儲方案之一。localStorage 存儲的數(shù)據(jù)只要用戶不去主動清除是永久存儲的,存儲的值只能是 string 類型,不能跨瀏覽器,不能跨域名訪問,存儲大小一般是 5M 左右?,F(xiàn)代前端項(xiàng)目基本都會用到localStorage ,下面的代碼片段對 localStorage 數(shù)據(jù)的存儲、獲取、清除進(jìn)行封裝。
const useStorage = (storageKey = "authorization") => {
const localKey = `devpoint.local.${storageKey}`;
const toJson = (str) => {
try {
return JSON.parse(str);
} catch {
return false;
}
};
const save = (data) => {
window.localStorage.setItem(localKey, JSON.stringify(data));
};
const get = () => {
const localData = window.localStorage.getItem(localKey);
if (localData && localData !== "") {
return toJson(localData);
} else {
return false;
}
};
/**
* 清除localStorage
*/
const clear = () => {
window.localStorage.setItem(localKey, "");
};
// 返回存儲對象處理方法
return {
save,
get,
clear,
};
};
const storageAuth = useStorage();
const loginInfo = {
username: "hballard",
age: 30,
};
storageAuth.save(loginInfo);
console.log(storageAuth.get());

2. JSON格式判斷
當(dāng)需要數(shù)據(jù)是否為 JSON 格式時(shí),下面的代碼片段將派上用場:
function isJSON(str) {
try {
JSON.parse(str);
} catch {
return false;
}
return true;
}
const data1 = "JavaScript";
const data2 = `{"title":"js"}`;
console.log(isJSON(data1)); // false
console.log(isJSON(data2)); // true
3. Array轉(zhuǎn)CSV
CSV 是當(dāng)今廣泛使用的電子表格,可以使用如下所示的簡單代碼段將數(shù)組轉(zhuǎn)換為 CSV 格式:
const arrayToCSV = (array, delimiter = ",") =>
array
.map((item) => item.map((value) => `"${value}"`).join(delimiter))
.join("\n");
const users = [
{ name: "hballard", age: 30 },
{ name: "sguzman", age: 24 },
{ name: "jrowe", age: 28 },
{ name: "plowe", age: 32 },
];
const arrayUsers = users.map((item) => Object.values(item));
console.log(arrayUsers);
// [
// [ 'hballard', 30 ],
// [ 'sguzman', 24 ],
// [ 'jrowe', 28 ],
// [ 'plowe', 32 ]
// ]
const strCsv1 = arrayToCSV(arrayUsers);
const strCsv2 = arrayToCSV(arrayUsers, ";");
console.log(strCsv1);
// "hballard","30"
// "sguzman","24"
// "jrowe","28"
// "plowe","32"
console.log(strCsv2);
// "hballard";"30"
// "sguzman";"24"
// "jrowe";"28"
// "plowe";"32"
4. 數(shù)字格式判斷
下面的代碼片段將展示如何檢查一個(gè)值或變量是否包含一個(gè)數(shù)字(整數(shù)、浮點(diǎn)數(shù)等)。
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
console.log(isNumber(100)); // true
console.log(isNumber(3.14)); // true
console.log(isNumber("3.14")); // true
console.log(isNumber("a3.14")); // false
console.log(isNumber("JavaScript")); // false
5. 數(shù)據(jù)類型判斷
數(shù)據(jù)類型判斷是在大部分項(xiàng)目中都會用上,特別對于 JavaScript ,對于不同的數(shù)據(jù)類型使用不同的方法。
const isCheck = (type, val) =>
![undefined, null].includes(val) && val.constructor === type;
console.log(isCheck(Array, ["a"])); // true
console.log(isCheck(Object, {})); // true
console.log(isCheck(ArrayBuffer, new ArrayBuffer())); // true
console.log(isCheck(Boolean, new Boolean(true))); // true
console.log(isCheck(RegExp, /./g)); // true
console.log(isCheck(Number, 0)); // true
6. 數(shù)組求和、平均值
reduce 方法在數(shù)組的每個(gè)元素上執(zhí)行提供的回調(diào)函數(shù)迭代器。它傳入前一個(gè)元素計(jì)算的返回值,結(jié)果是單個(gè)值,它是在數(shù)組的所有元素上運(yùn)行迭代器的結(jié)果。對于數(shù)組求和、平均值等場合非常實(shí)用。
數(shù)組求和
const sum = (...array) => [...array].reduce((acc, current) => acc + current, 0);
const testArray = [1, 2, 3, 4, 5];
console.log(sum(1, 2, 3, 4, 5)); // 15
console.log(sum(...testArray)); // 15
平均值
const average = (...numbers) =>
numbers.reduce((acc, current) => acc + current, 0) / numbers.length;
const testArray1 = [1, 2, 3, 4, 5];
console.log(average(...testArray1)); // 3
console.log(average(1, 2, 3, 4, 5)); // 3
7. 函數(shù)鏈
函數(shù)鏈,應(yīng)該算是代碼組織形式,這里放到代碼片段中,希望可以對項(xiàng)目代碼組織有一定的啟發(fā)。
function CusModal() {
const This = this;
this.options = {
theme: "default",
title: "modal",
visible: false,
};
const setOptions = function (key, value) {
This.options[key] = value;
};
this.setTheme = function (theme) {
setOptions("theme", theme);
return this;
};
this.setTitle = function (title) {
setOptions("title", title);
return this;
};
this.show = function () {
setOptions("visible", true);
};
this.close = function () {
setOptions("visible", false);
};
this.getOptions = function () {
return this.options;
};
}
const modalHelper = new CusModal();
// 設(shè)置彈窗主題、設(shè)置標(biāo)題、顯示
modalHelper.setTheme("dark").setTitle("發(fā)布文章窗口").show();
console.log(modalHelper.getOptions()); // { theme: 'dark', title: '發(fā)布文章窗口', visible: true }
8. 科學(xué)計(jì)數(shù)完整顯示
在項(xiàng)目中有遇到 API 返回?cái)?shù)字是以科學(xué)計(jì)數(shù)法的方式,在頁面上需要顯示完整的數(shù)字,通常并不清楚科學(xué)計(jì)數(shù)的數(shù)字是小數(shù)點(diǎn)多少位,因此在精度方面不好固定。下面代碼實(shí)現(xiàn)了一個(gè)小數(shù)點(diǎn)后大于 0 的數(shù)字三位,如下:
function flatNumber(num) {
const strNumber = num.toFixed(30);
console.log(strNumber);
const arrayNumbers = [...strNumber];
const numberIndex = arrayNumbers.findIndex(
(item) => parseInt(item, 10) > 0
);
const precision = numberIndex >= 0 ? numberIndex + 1 : 0;
return num.toFixed(precision);
}
const number = 1.71604938271605e-8;
console.log(number.toFixed(30)); // 0.000000017160493827160499945830
console.log(flatNumber(number)); // 0.0000000172
9. 定時(shí)器
定時(shí)器,在項(xiàng)目開發(fā)過程中結(jié)果過,使用定時(shí)器需要嚴(yán)格控制定時(shí)器的啟動與關(guān)閉,避免過多定時(shí)器沒有關(guān)閉導(dǎo)致內(nèi)存泄露,下面代碼實(shí)現(xiàn)了一個(gè)定時(shí)器的開啟與停止:
class Timer {
constructor(fn, delay) {
this._triggerTimer = null;
this._delay = delay;
this._fn = fn;
}
stop() {
if (this._triggerTimer) {
clearTimeout(this._triggerTimer);
this._triggerTimer = null;
}
}
begin() {
this.stop();
this._triggerTimer = setTimeout(() => {
this._fn();
}, this._delay);
}
}
// 下面是使用方法
let timerCount = 0;
const timerHelper = new Timer(() => {
timerCount++;
if (timerCount < 5) {
console.log(timerCount);
timerHelper.begin();
} else {
timerHelper.stop();
}
}, 2000);
timerHelper.begin();
10. 時(shí)間格式化
JavaScript中時(shí)間相關(guān)的腳本庫有很多,如 Moment 和 Luxon,提供比較豐富的時(shí)間相關(guān)的方法,這里介紹原生方法的實(shí)現(xiàn)。
const formatDate = (date, formatStr = "YYYY-MM-DD") => {
date = new Date(date);
const padStart = (str) => str.toString().padStart(2, "0");
const month = date.getMonth() + 1;
const year = date.getFullYear();
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
return formatStr
.replace(/\bYYYY\b/g, year)
.replace(/\bYY\b/g, `${year}`.substring(2))
.replace(/\bMM\b/g, padStart(month))
.replace(/\bM\b/g, month)
.replace(/\bDD\b/g, padStart(day))
.replace(/\bD\b/g, day)
.replace(/\bHH\b/g, padStart(hours))
.replace(/\bhh\b/g, hours)
.replace(/\bmm\b/g, padStart(minutes))
.replace(/\bss\b/g, padStart(seconds));
};
console.log(formatDate(Date.now())); // 2021-11-03
console.log(formatDate(Date.now(), "YYYY-MM-DD HH:mm:ss")); // 2021-11-03 18:49:29
11. 類私方法
JavaScript 有自己的方法來創(chuàng)建類私有成員,但目前還處于ES2020試驗(yàn)草案中,并且語法比較奇怪,以 # 作為前綴。下面代碼片段使用閉包、作用域來實(shí)現(xiàn)類的私有域。
const Helper = (() => {
// 這里定義私有方法 defaultValue
const defaultValue = (val, defVal) => {
if (val && val !== "") {
return val;
} else {
return defVal;
}
};
const apiEndpoint = "/Auth";
// 對外暴露的類
class Utility {
constructor() {
this.loginPath = `${apiEndpoint}/login`;
}
getVal(key, defVal) {
return defaultValue(key, defVal);
}
}
return Utility;
})();
const testHelper = new Helper();
console.log(testHelper.getVal(undefined, 0)); // 0
console.log(testHelper.loginPath); // /Auth/login
12. 空值判斷
正如上面說的,判斷空值,在不同的項(xiàng)目下有不同的解釋,下面的代碼片段可以判斷所有類型的空值。
const isEmpty = (x) => {
if (Array.isArray(x) || typeof x === "string" || x instanceof String) {
return x.length === 0;
}
if (x instanceof Map || x instanceof Set) {
return x.size === 0;
}
if ({}.toString.call(x) === "[object Object]") {
return Object.keys(x).length === 0;
}
if (!isNaN(parseFloat(x)) && isFinite(x)) {
return false;
}
return !x;
};
console.log(isEmpty(null)); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty([])); // true
console.log(isEmpty({})); // true
console.log(isEmpty("")); // true
console.log(isEmpty(new Set())); // true
console.log(isEmpty(0));
代碼整潔技巧
項(xiàng)目開發(fā)中,除了完成相應(yīng)功能需要,還需要去重新閱讀其代碼,去發(fā)掘代碼整潔的方式,代碼優(yōu)化是一個(gè)沒有標(biāo)準(zhǔn)答案的工作,但有一些推薦的方式。下面總結(jié)了一些代碼整潔的技巧。在這里推薦兩個(gè)學(xué)些代碼的不錯(cuò)的網(wǎng)站 https://1loc.dev/ 和 30secondsofcode。
1. 短循環(huán)
你知道在 JavaScript 中可以在一行中縮短循環(huán)嗎?這意味著可以為循環(huán)編寫更少的代碼。
const provinces = ["Guangdong", "Jiangxi", "Hunan", "Fujian"];
// 常規(guī)
for (let i = 0, len = provinces.length; i < len; i++) {
console.log(provinces[i]);
}
// 短循環(huán)
for (const province of provinces) console.log(province);
2. 數(shù)組長度變更
在 JavaScript 可以通過使用 length 方法調(diào)整數(shù)組的大小, length 不僅用于獲取數(shù)組的長度,還可以對數(shù)組進(jìn)行切片。
const array1 = [1, 2, 3, 4, 5, 6];
const array2 = ["Python", "JavaScript", "C++", "Dart"];
array1.length = 3;
array2.length = 1;
console.log(array1); // [1, 2, 3]
console.log(array2); // ["Python"]
3. 浮點(diǎn)數(shù)轉(zhuǎn)換為整數(shù)
要將浮點(diǎn)數(shù)轉(zhuǎn)換為整數(shù),通??梢允褂?Math.floor()、Math.round() 和 Math.ceil() 方法,這里介紹一種簡短的方式,即按位 OR ,如下:
// 常規(guī)
console.log(Math.floor(3.14)); // 3
// 簡短
console.log(3.14 | 0); // 3
4. 數(shù)組去重
通過利用 JavaScript 數(shù)據(jù)類型 Set 特征,關(guān)于 Set 的使用可以參閱《JavaScript中的Set數(shù)據(jù)操作:交集、差集、交集、對稱差集》。使用Set可以快速的實(shí)現(xiàn)數(shù)組去重,如下:
const removeDupli = (arr) => [...new Set(arr)];
console.log(removeDupli([2, 2, 2, 11, 3])); // [ 2, 11, 3 ]
console.log(removeDupli([2, 0, 2, 1, 11, 1])); // [ 2, 0, 1, 11 ]
5. 數(shù)組合并
這段代碼將兩個(gè)數(shù)組合并為一個(gè)數(shù)組,這是一種簡單快捷的方法,無需使用循環(huán)。
const lang1 = ["JavaScript", "Python", "C++"];
const lang2 = ["C#", "Dart", "Clojure"];
const merge = [...lang1, ...lang2];
console.log(merge); // [ 'JavaScript', 'Python', 'C++', 'C#', 'Dart', 'Clojure' ]
這個(gè)是擴(kuò)展運(yùn)算符 ... 的比較經(jīng)典的使用方法。更多擴(kuò)展運(yùn)算符的使用請參閱《ES6中擴(kuò)展運(yùn)算符的8種用法》
6. 獲取數(shù)組最后一項(xiàng)
當(dāng)需要獲取數(shù)組的最后一個(gè)元素時(shí),最簡短的方式是使用 slice 方法,只需將負(fù)數(shù)作為參數(shù),它就會從最后一個(gè)索引開始對數(shù)組進(jìn)行切片。
const array = [1, 3, 4, 5, 6, 9, 10, 12];
console.log(array.slice(-1)); // [12]
console.log(array.slice(-2)); // [10, 12]
console.log(array.slice(-4)); // [6, 9 ,10, 12]
7. 對象合并
將多個(gè)對象合并為一個(gè)。在 JavaScript 中,可以使用 ... 方法,這也是實(shí)現(xiàn)此需求最簡潔的方法,如下:
const article1 = { title: "JavaScript特征", lang: "js" };
const article2 = { view: 10, time: "2021", lang: "javascript" };
const article = {
...article1,
...article2,
};
console.log(article); // { title: 'JavaScript特征', lang: 'javascript', view: 10, time: '2021' }
如有相同的屬性,后面的會覆蓋前面的。
8. 數(shù)組最大數(shù)最小數(shù)
這是一種查找數(shù)組中最大數(shù)或者最小數(shù)的方法之一,也可以通過循環(huán)來實(shí)現(xiàn)這一需求,下面分享一種簡單方法:
const findMax = (arrayNumbers) => Math.max(...arrayNumbers);
const findMin = (arrayNumbers) => Math.min(...arrayNumbers);
const arrNumbers = [10, 13, 1, 48, 6, 216];
console.log(findMax(arrNumbers)); // 216
console.log(findMin(arrNumbers)); // 1
總結(jié)
JavaScript 的靈活性使得編程充滿技巧,作為 JavaScript 開發(fā)人員,要感覺自己就是一個(gè)魔術(shù)師,合理靈活的利用其技巧,不段提升對代碼的組織能力。
媒體矩陣
infoQ:https://xie.infoq.cn/article/f0df2d71ac009c48a6e4243b5