JavaScript 开发技巧

1、String

1 // ***** String *****
2   /**
3    * 金钱格式化
4   */
5   let money = num => num.toString().replace(/\B(?=(\d{4})+(?!\d))/g, '.')
6   let m = money(20310421032)
7   console.log(m); // 203.1042.1032
 1 /**
 2    * 生成随机id
 3    *
 4    * toString() 有一个可选参数radix,就是进制。默认值为 10,可转换的基数 2-36。
 5    * 如果转换的基数大于 10,则会使用字母来表示大于 9的数字。
 6    * 例如,基数为 16的情况,则会使用 a-f的字母来表示 10-15。
 7    * 如果基数是 36,就会把数字表示为由 0-9 a-z 组成的 36进制字符串
 8   */
 9   let randomId = num => Math.random().toString(36).substr(3, num)
10   let id = randomId(4)
11   console.log(id); // xiw2
1 /**
2    * 生成随机 hex 颜色值
3   */
4   let randomColor = () => '#' + Math.floor(Math.random() * '0xffffff').toString(16).padEnd(6, '0')
5   let color = randomColor()
6   console.log(color); // #c228c3
1 /**
2    * 操作URL查询参数
3   */
4   let url = '?name=hh&id=12345&age=18'
5   // let params = new URLSearchParams(location.search.replace(/\?/ig, ''))
6   let params = new URLSearchParams(url.replace(/\?/ig, ''))
7   console.log(params.has('age')); // true
8   console.log(params.get('name')); // hh

2、Number

1 /**
2    * 取整数
3   */
4   let num1 = ~~ 1.623232
5   let num2 = 2.323243 | 0
6   let num3 = 3.43243243 >> 0
7   console.log(num1, num2, num3); // 1 2 3
8   console.log(Math.floor(4.54543), Math.ceil(-5.543543)); // 4 -5
1 /**
2    * 前、后 补任意字符
3   */
4   const startStr = (num, len) => num.toString().padStart(len, "a");
5   const endStr = (num, len) => num.toString().padEnd(len, 'b')
6   const start = startStr(169, 5);
7   const end = endStr(26, 9)
8   console.log(start, 'start'); // aa168
9   console.log(end, 'end'); // 26bbbbbbb
1 /**
2    * 转数值
3   */
4   let n1 = +null
5   let n2 = +''
6   let n3 = +false
7   let n4 = +'123'
8   let n5 = '123' * 1
9   console.log(n1, n2, n3, n4, n5); // 0 0 0 123 123
1 /**
2    * 时间戳
3   */
4   let time1 = +new Date('2021-5-28')
5   let time2 = new Date('2021/5/28').getTime()
6   console.log(time1, time2, time1 === time2); // 1622131200000 1622131200000 true
1 /**
2    * 保留小数
3   */
4   let r = (n, m) => Math.round(n * 10 ** m) / 10 ** m
5   let round = r(6.949243, 3)
6   console.log(round); // 6.949
 1 /**
 2    * 位运算
 3    * JavaScript 使用 32 位按位运算数
 4    * & 如果位数都是 1,则位运算返回 1
 5    * | 如果其中一位是 1, 则位运算返回 1
 6    * ^ 数位是不同的则返回 1
 7    * << 零填充的左移。一个或多个零数位从右被推入,最左侧的数位被移除
 8    * >>> 零填充的右移。一个或多个零数位从左侧被推入,最右侧的数位被移出
 9   */
10   let and1 = 0 & 0
11   let and2 = 0 & 1
12   let and3 = 1 & 0
13   let and4 = 1 & 1
14   console.log(and1, and2, and3, and4); // 0 0 0 1
15 
16   let or_1 = 0 | 0
17   let or_2 = 0 | 1
18   let or_3 = 1 | 0
19   let or_4 = 1 | 1
20   console.log(or_1, or_2, or_3, or_4); // 0 1 1 1
21 
22   let xor_1 = 0 ^ 0
23   let xor_2 = 0 ^ 1
24   let xor_3 = 1 ^ 0
25   let xor_4 = 1 ^ 1
26   console.log(xor_1, xor_2, xor_3, xor_4); // 0 1 1 0
27 
28   // 5 的二进制 00000000000000000000000000000101
29   let bit_1 = 5 << 1
30   console.log(bit_1) // (10) 00000000000000000000000000001010
31 
32   let bit_2 = 5 >>> 1
33   console.log(bit_2); // (2) 00000000000000000000000000000010
1 /**
2    * 进制转换
3   */
4   let bin = (num) => (num >>> 0).toString(2)
5   console.log(bin(10)); // 101
6 
7   let dec = (num) => parseInt(num, 2).toString(10)
8   console.log(dec(1010)); // 10
1 /**
2    * 判断奇数、偶数
3   */
4   let oddOrEven2 = num => (num & 1) ? '奇' : '偶'
5   console.log(oddOrEven2(-2), oddOrEven2(-1), oddOrEven2(0), oddOrEven2(1)); // 偶 奇 偶 奇
1 /**
2    * 取最大、最小值
3   */
4   let a = [1, 2, 3, '20']
5   let min = Math.min(...a)
6   let max = Math.max(...a)
7   console.log(min, max); // 1 20
1 /**
2    * 区间随机数
3   */
4   let random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
5   let num4 = random(-1, 1)
6   console.log(num4); // 1

3、Boolean

 1 /**
 2    * 判断数据类型
 3    * 可判断类型:undefined、null、string、number、boolean、array、object、symbol、
 4    * date、regexp、function、asyncfunction、arguments、set、map、weakset、weakmap
 5   */
 6   function dataType(val, type) {
 7     let type1 = Object.prototype.toString.call(val).replace(/\[object (\w+)\]/, '$1').toLowerCase()
 8     return type ? type1 === type : type1
 9   }
10   console.log(dataType('aaa')); // string
11   console.log(dataType(1111)); // number
12   console.log(dataType(false)); // boolean
13   console.log(dataType([], 'array'), '0'); // true
1 /**
2    * 判断空数组
3   */
4   let arr = []
5   let arrFlag = Array.isArray(arr) && !arr.length
6   console.log(arrFlag); // true
1 /**
2    * 判断空对象
3   */
4   let obj = {}
5   let objFlag = dataType(obj, 'object') && !Object.keys(obj).length
6   console.log(objFlag); // true
 1  function Fun() {
 2     return 'fun'
 3   }
 4 
 5   /**
 6    * 为非假时执行
 7    * undefined、null、''、0、false、NaN
 8   */
 9   let flag = null
10   console.log(!flag && Fun()); // fun
1 /**
2    * 数组不为空时执行
3   */
4   let arr1 = []
5   console.log(arr1.length && Fun()); // 0
1 /**
2    * 对象不为空时执行
3   */
4   let obj1 = {}
5   let o = Object.keys(obj1).length && Fun()
6   console.log(o); // 0
 1 /**
 2    * switch/case使用区间
 3   */
 4   let age = 300
 5   switch (true) {
 6     case isNaN(age):
 7       console.log('not a number!');
 8       break;
 9     case age < 18:
10       console.log('yes');
11       break;
12     case age >= 18:
13       console.log('no');
14       break;
15 
16     default:
17       console.log('please set your age');
18       break;
19   }

3、Array

1 /**
2    * 数组克隆
3   */
4   let arr_1 = [0, 1, 2, 3]
5   let arr_2 = [...arr_1, 0, 4, 'a']
6   console.log(arr_2); // [0, 1, 2, 3, 0, 4, "a"]
1 /**
2    * 数组合并
3   */
4   let arr_3 = [0, 1, 2]
5   let arr_4 = [3, 4, 'b']
6   let arrList = [...arr_3, ...arr_4]
7   console.log(arrList); // [0, 1, 2, 3, 4, "b"]
1 /**
2    * 数组去重
3   */
4   let arr_a = [1, 1, 2, 2, null, null]
5   let arr_5 = [...new Set([...arr_a, 3, 3, 2, null])]
6   console.log(arr_5); // [1, 2, null, 3]
1 /**
2    * 数组清空
3   */
4   let arr_b = [1, 2, 3]
5   arr_b.length = 0
6   console.log(arr_b); // []
1 /**
2    * 数组截断
3   */
4   let arr_c = ['1', '2', '3', '4']
5   arr_c.length = 2
6   console.log(arr_c); // ["1", "2"]
1 /**
2    * 交换赋值
3   */
4   let aa = 1
5   let bb = 3
6   [aa, bb] = [bb, aa]
7   console.log(aa, bb); // 3 1
1 /**
2    * 过滤空值 (undefined、null、''、0、false、NaN)
3   */
4   let arr_d = [1, 'a', undefined, null, '', 0, false, NaN, 1, 2, 'a', 'b'].filter(Boolean)
5   console.log(arr_d); // [1, "a", 1, 2, "a", "b"]
 1 /**
 2    * 异步累计
 3   */
 4   async function Func(deps) {
 5     return deps.reduce(async(t, v) => {
 6       const dep = await t
 7       const version = await Todo(v)
 8       dep[v] = version
 9       return dep
10     }, Promise.resolve({}))
11   }
12   // const result = await Func() // 需要在 async 包围下使用
1 /**
2    * 统计数组成员个数
3   */
4   let arr_e = [0, 1, 1, 2, 3, 3]
5   let count = arr_e.reduce((t, v) => (t[v] = t[v] ? ++t[v] : 1, t), {})
6   console.log(count); // {0: 1, 1: 2, 2: 1, 3: 2}
1 /**
2    * 解构数组嵌套
3   */
4   let arr_f = [0, 1, [2, 3, [4, 5]]]
5   let [a1, b1, [c1, d1, [e1, f1]]] = arr_f
6   console.log(a1, b1, c1, d1, e1, f1); // 0 1 2 3 4 5
1 /**
2    * 解构数组成员别名
3   */
4   let arr_g = [0, 1, 2]
5   let {0: a2, 1: b2, 2: c2} = arr_g
6   console.log(a2, b2, c2); // 0 1 2
1 /**
2    * 解构数组成员默认值
3   */
4   let [a3, b3, c3 = 3, d3 = 4] = arr_g
5   console.log(a3, b3, c3, d3); // 0 1 2 4
1 /**
2    * 随机获取数组成员
3   */
4   let arr_h = [0, 1, 2, 'a', 'b', 'c']
5   let randomItem = arr_h[Math.floor(Math.random() * arr_h.length)]
6   console.log(randomItem); // b
1 /**
2    * 创建指定长度数组
3   */
4   let arr_i = [...new Array(3).keys()]
5   console.log(arr_i); // 0 1 2
1 /**
2    * 创建值相同的,指定长度数组
3   */
4   let arr_j = [...new Array(4).fill('a')]
5   console.log(arr_j); // ['a', 'a', 'a', 'a']
 1 /**
 2    * reduce 代替 map 和 filter
 3   */
 4   // let arr_g = [0, 1, 2]
 5   let mapArr = arr_g.map(m => m * 2)
 6   let reduceArr = arr_g.reduce((t, v) => (t.push(v * 2), t), [])
 7   console.log(mapArr, reduceArr); // [0, 2, 4] [0, 2, 4]
 8 
 9   let filterArr = arr_g.filter(f => f > 0)
10   let reduceF = arr_g.reduce((t, v) => (v > 0 && t.push(v), t), [])
11   console.log(filterArr, reduceF); // [1, 2] [1, 2]
12 
13   let arrM = arr_g.map(m => m * 2).filter(f => f > 2)
14   let arrR = arr_g.reduce((t, v) => (v = v *2, v > 2 && t.push(v), t), [])
15   console.log(arrM, arrR); // [4] [4]

4、Object

1 /**
2    * 克隆对象
3   */
4   let object = {a: 0, b: 1, c: 2}
5   let obj_1 = {...object, d: '4'}
6   let obj_2 = JSON.parse(JSON.stringify(object))
7   console.log(obj_1, obj_2); // {a: 0, b: 1, c: 2, d: "4"} {a: 0, b: 1, c: 2}
1 /**
2    * 合并对象
3   */
4   let obj_3 = {...obj_1, ...obj_2}
5   console.log(obj_3); // {a: 0, b: 1, c: 2, d: "4"}
 1 /**
 2    * 对象字面量(可用于获取环境变量)
 3   */
 4   let evn = 'prod'
 5   let link = {
 6     dev: 'development',
 7     test: 'testing',
 8     prod: 'production'
 9   }[evn]
10   console.log(link); // production
 1 /**
 2    * 对象变量属性
 3   */
 4   let flag1 = false
 5   let obj_4 = {
 6     a: 0,
 7     b: 1,
 8     [flag ? 'c' : 'x']: 2
 9   }
10   console.log(obj_4); // {a: 0, b: 1, x: 2}
1 /**
2    * 创建纯空对象
3   */
4   let obj_5 = Object.create(null)
5   Object.prototype.a = 0
6   console.log(obj_5); // {}
1 /**
2    * 过滤对象无用属性
3   */
4   let obj_6 = {rest: 'rest', x: 'x', y: 'y'}
5   let {rest, ...rest_1} = obj_6
6   console.log(rest_1); // {x: "x", y: "y"}
1 /**
2    * 解构对象属性嵌套
3   */
4   let obj_7 = {a: 0, b: '1', c: {d: 2, e: '3'}}
5   let {c: {d, e}} = obj_7
6   console.log(d, e); // 2 '3'
1 /**
2    * 解构对象属性别名
3   */
4   let {rest: rest_3, x, y: y1} = obj_6
5   console.log(rest_3, x, y1); // rest x y
1 /**
2    * 解构对象属性默认值
3   */
4   let obj_8 = {v: 'v', p: 'p', k: 'k'}
5   let {v, p = 8, z = 9} = obj_8
6   console.log(v, p, z); // v p 9

5、Function

 1 /**
 2    * 自执行函数
 3   */
 4   // let Func_1 = function() {
 5   //   console.log('fun_1');
 6   // }()
 7 
 8   (function() {
 9     console.log('fun_2');
10   })()
11 
12   // (function() {
13   //   console.log('fun_3');
14   // }())
15 
16   // [function() {
17   //   console.log('fun_4');
18   // }()]
19 
20   // + function() {
21   //   console.log('fun_5');
22   // }()
23   // - function() {
24   //   console.log('fun_6');
25   // }()
26   // ~ function() {
27   //   console.log('fun_7');
28   // }()
29   // ! function() {
30   //   console.log('fun_8');
31   // }()
32 
33   // new function() {
34   //   console.log('1');
35   // }
36   // new function() {
37   //   console.log('2');
38   // }()
39   // void function() {
40   //   console.log('3');
41   // }()
42   // typeof function() {
43   //   console.log('4');
44   // }()
45   // delete function() {
46   //   console.log('5');
47   // }()
48 
49   // 1, function() {
50   //   console.log('6');
51   // }()
52   // 1 ^ function() {
53   //   console.log('7');
54   // }()
55   // 1 > function() {
56   //   console.log('8');
57   // }()
1 /**
2    * 隐式返回值
3    * 只能用于 单语句返回值箭头函数 ,如果返回值是对象必须使用()包住
4   */
5   let f_1 = name => 'i love ' + name, name
6   console.log(f_1('yy')); // i love yy
 1 /**
 2    * 一次性函数
 3    * 适用于运行一些只需执行一次的初始化代码
 4   */
 5   function f_2() {
 6     console.log('f_x');
 7     fun_2 = function() {
 8       console.log('f_y');
 9     }
10     // console.log(fun_2());
11   }
12   console.log(f_2()); // f_x undefined
 1 /**
 2    * 惰性载入函数
 3    * 函数内判断分支较多较复杂时可大大节约资源开销
 4   */
 5   function F_3(a, b) {
 6     if (a === b) {
 7       console.log('a');
 8     } else {
 9       console.log('b');
10     }
11   }
12   console.log(F_3(1, 2)); // b undefined
13 
14   function F_4(a, b) {
15     if (a === b) {
16       Func_4 = function() {
17         console.log('a_4');
18       }
19     } else {
20       Func_4 = function() {
21         console.log('b_4');
22       }
23     }
24     return Func_4()
25   }
26   console.log(F_4(1, 1)); // a_4 undefined
 1 /**
 2    * 检测非空参数
 3   */
 4   function isRequired() {
 5     console.error('params is required !');
 6     // throw new Error('params is required !')
 7   }
 8   function F_5(name = isRequired()) {
 9     console.log('i love ' + name);
10   }
11   console.log(F_5()); // params is required !
12   console.log(F_5('mm')); // i love mm
1 /**
2    * 优雅处理错误信息
3   */
4   try {
5     Func_6()
6   } catch (e) {
7     console.error(e.message);
8     // location.href = "https://www.cnblogs.com/" + e.message;
9   }
  
1 // 处理 async await 参数
2   function asyncTo(promise) {
3     return promise.then(data => [null, data]).catch(err => [err])
4   }
5   async function F_7() {
6     let [err, res] = await asyncTo() // async 包围下使用
7     console.log(err, res);
8   }
9   F_7()
 1 /**
 2    * 优雅处理多个函数返回值
 3   */
 4   function F_8() {
 5     return Promise.all([
 6       fetch('/user'),
 7       fetch('/list')
 8     ])
 9   }
10   // let [user, list] = await F_8() // 在 async 下使用
 1  /**
 2    * 深拷贝
 3   */
 4   function deepCopy(data, val) {
 5     var val = val || {}
 6     for (const i in data) {
 7       if (typeof data[i] === 'object') {
 8         val[i] = data[i].constructor === Array ? [] : {}
 9         deepCopy(data[i], val[i])
10       } else {
11         val[i] = data[i]
12       }
13     }
14     return val
15   }

 

6、DOM

 1 /**
 2    * 自适应页面
 3    * 页面基于一张设计图但需要做多款机型自适应,元素尺寸使用 rem 设置
 4   */
 5   function auto(width = 750) {
 6     let target = document.documentElement
 7     target.clientWidth >= 600
 8       ? target.style.fontSize = '80px'
 9       : target.style.fontSize = target.clientWidth / width * 100 + 'px'
10   }
11   auto()
 1 /**
 2    * 过滤 XSS
 3   */
 4   function filterXss(content) {
 5     let el = document.createElement('div')
 6     el.innerText = content
 7     let res = el.innerHTML
 8     el = null
 9     console.log(res); // &lt;p&gt;2233&lt;/p&gt;
10     return res
11   }
12   filterXss('<p>2233</p>')
1 /**
2    * 存取 Localstorage
3   */
4   localStorage.setItem('item', JSON.stringify('{item: 11111}'))
5   let local = JSON.parse(localStorage.getItem('item'))
6   console.log(local);

 

posted @ 2021-06-02 15:34  里里昂  阅读(71)  评论(0)    收藏  举报