值得收藏的15個JavaScript語句

JavaScript 可以處理很多事情,從復雜的框架到API的處理,需要學習的東西太多了。今天來分享 15 個簡單且可能常用到函數語句。
1. 兩個日期間的天數
這個是一個常見的功能,在涉及統計相關的需求中基本都需要使用。
const diffDays = (startDate, endDate) =>
Math.ceil(
Math.abs(new Date(startDate) - new Date(endDate)) /
(1000 * 60 * 60 * 24)
);
console.log(diffDays("2021-06-01", "2021-06-23")); // 22
2. 首字母大寫
使用此函數,可以輕松將一串字符串的第一個字母大寫。
const capitalize = (strContent) =>
`${strContent.charAt(0).toUpperCase()}${strContent.slice(1)}`;
console.log(capitalize("devPoint")); // DevPoint
3. 字符串轉數字
在與后臺API交互數據,通常在From表單中輸入的數字一般為數字字符串,在提交到后臺前需要轉為數字。而使用類型強制將字符串轉換為數字是最直接的方法。
const toNumber = (str) => +str;
// 顯式地將字符串轉換為數字
const toNumber2 = (str) => Number(str);
console.log(toNumber("100")); // 100
console.log(toNumber2("99")); // 99
4. 數字轉字符串
const toString = (num) => num + "";
// 顯式地將字符串轉換為數字
const toString2 = (num) => num.toString();
const number = 100.0;
console.log(typeof toString(number)); // string
console.log(typeof toString2(number)); // string
5. 驗證數組是否為空
可以使用 isArray 方法確定為數組然后檢查數組的長度是否大于 0 。
const isNotEmpty = (arr) => Array.isArray(arr) && arr.length > 0;
console.log(isNotEmpty([6, 7, 8])); // true
console.log(isNotEmpty([])); // false
6. 數組合并
合并數組有很多種不同的方式,如 concat 方法、擴展操作符 …。如果需要考慮去重,則可以考慮 Set 。
const mergeArray = (a, b) => a.concat(b);
const mergeBySpread = (a, b) => [...a, ...b];
const mergeBySet = (a, b) => [...new Set(a.concat(b))];
const arr1 = [6, 7, 8, "b"];
const arr2 = ["a", 7, 8, "b"];
console.log(mergeArray(arr1, arr2)); // [6, 7, 8, 'b','a', 7, 8, 'b']
console.log(mergeBySpread(arr1, arr2)); // [6, 7, 8, 'b','a', 7, 8, 'b']
console.log(mergeBySet(arr1, arr2)); // [ 6, 7, 8, 'b', 'a' ]
7. 數組排序
JavaScript 的內置排序方法很不好用,它不能很好地處理數字,所以這個函數是一種對數組進行排序的簡單方法。
const sort = (arr) => arr.sort((a, b) => a - b);
console.log(sort([10, 8, 2, 68, 3])); // [ 2, 3, 8, 10, 68 ]
8. 生成隨機十六進制顏色
生成RGB顏色稍微簡單一點,但創建隨機的十六進制顏色可能會有點復雜。這個函數將可以生成一個隨機的十六進制顏色。
const randomColor = () =>
`#${Math.random().toString(16).slice(2, 8).padStart(6, "0")}`;
const randomColor2 = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;
console.log(randomColor()); // #4fd21f
console.log(randomColor2()); // #2c456b
9. 獲取Cookie
前端通過 document.cookie 獲取當前頁面的 cookie ,然后檢索置頂名稱的 cookie 值并將它返回。
const getCookie = (name, strCookie) =>
`; ${strCookie}`.split(`; ${name}=`).pop().split(";").shift();
console.log(getCookie("_ga", document.cookie)); // GA1.2.918318285.1606740576
10. 獲取用戶選擇的文本
當用戶使用光標選擇文本時,可以使用 window 對象上的 getSelection 方法來獲取。
const getSelectedText = () => window.getSelection().toString();
console.log(getSelectedText());
11. 變量值交換
有時,需要交換 2 個變量的值,或者面試過程常見,如何在沒有第三個變量的情況下交換兩個變量的值。下面代碼可以簡單做到:
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
12. 獲取數組最后一項
通常獲取數組最后一項是通過數組長度來獲取,這里介紹 slice 方法的妙用。
const getLast = (arr) => arr.slice(-1)[0];
const arrTest = [1, 2, 3, 4, 5];
console.log(getLast(arrTest)); // 5
13. 使用方括號動態設置對象的鍵
有些時候,在創建對象時,希望根據特定的條件或變量更改對象的屬性名,就可以借助方括號 [] 。
const dynamic = "url";
const item = {
brand: "DevPoint",
[dynamic]: "devpoint.cn",
};
console.log(item); // { brand: 'DevPoint', url: 'devpoint.cn' }
14. 使用 || 設置默認值
為變量設置默認值,避免無法處理的數據出現異常。
const getTitle = (obj)=>obj.title || "";
15. 使用 length 縮短數組
縮短數組的簡單方法是重新定義它的長度屬性,不過這樣會更改數組,意味著將丟失數組中其他值。
const shortenArray = (arr, count) => {
arr.length = count;
return arr;
};
const array = [0, 1, 2, 3, 4, 5, 6, 6, 8, 9];
const shortArr = shortenArray(array, 4);
console.log(array); // [ 0, 1, 2, 3 ]
console.log(shortArr); // [ 0, 1, 2, 3 ]
// 修改后
const shortenArray = (arr, count) => {
const arrTemp = [...arr];
arrTemp.length = count;
return arrTemp;
};
const array = [0, 1, 2, 3, 4, 5, 6, 6, 8, 9];
const shortArr = shortenArray(array, 4);
console.log(array); // [0, 1, 2, 3, 4, 5, 6, 6, 8, 9]
console.log(shortArr); // [ 0, 1, 2, 3 ]