1.格式化金錢值
const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const money = ThousandNum(20190214);
// money => "20,190,214"
2.取整 代替正數的 Math.floor(),代替負數的 Math.ceil()
const num1 = ~~ 1.69; const num2 = 1.69 | 0; const num3 = 1.69 >> 0; // num1 num2 num3 => 1 1 1
3.轉數值 只對 null 、"" 、false 、數值字串 有效
const num1 = +null; const num2 = +""; const num3 = +false; const num4 = +"169"; // num1 num2 num3 num4 => 0 0 0 169
4.精確小數
const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal; const num = RoundNum(1.69, 1); // num => 1.7
5.取最小最大值
const arr = [0, 1, 2]; const min = Math.min(...arr); const max = Math.max(...arr); // min max => 0 2
6.是否為空物件
const obj = {}; const flag = DataType(obj, "object") && !Object.keys(obj).length; // flag => true
7.判斷資料型別
function DataType(tgt, type) { const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1").toLowerCase(); return type ? dataType === type : dataType; } DataType("liner"); // "string" DataType(2020630); // "number" DataType(true); // "boolean" DataType([], "array"); // true DataType({}, "array"); // false
8.克隆陣列
const _arr = [0, 1, 2]; const arr = [..._arr]; // arr => [0, 1, 2]
9.合并陣列
const arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; const arr = [...arr1, ...arr2]; // arr => [0, 1, 2, 3, 4, 5];
10.去重陣列
const arr = [...new Set([0, 1, 1, null, null])]; // arr => [0, 1, null]
11.截斷陣列
const arr = [0, 1, 2]; arr.length = 2; // arr => [0, 1]
12.交換賦值
let a = 0; let b = 1; [a, b] = [b, a]; // a b => 1 0
13.克隆物件
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 }
14.合并物件
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 }

為什么 obj 不是 {a:0,b:1,c:2,d:4,e:5} 而是上面結果 下面相同的例子就可以說明

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/49978.html
標籤:JavaScript
上一篇:Rematch的深入學習與實戰應用(一),簡易數字計數器
下一篇:JavaScript例外報錯處理:Uncaught TypeError: xxx is not a function
