今天,学会这10个JS代码段就够了!

开发 前端
在本文中,我们来看一下,如何学会这10个JS代码段,让我们一起学习一下吧!

 [[408192]]

用 apply 将数组各项添加到另一个数组

  1. const array = ['a''b']; 
  2. const elements = [0, 1, 2]; 
  3. array.push.apply(array, elements); 
  4. console.info(array); // ["a""b", 0, 1, 2] 

函数只执行一次

  1. function once (fn){ 
  2.   let called = false 
  3.   return function () { 
  4.     if (!called) { 
  5.       called = true 
  6.       fn.apply(this, arguments) 
  7.     } 
  8.   } 
  9.  
  10. function func (){ 
  11.     console.log(1); 
  12.  
  13. //调用 
  14. let onlyOnce = once(func); 
  15.  
  16. // 测试 
  17. onlyOnce(); // 1 
  18. onlyOnce(); // 不执行 

防抖

  1. /** 
  2.  * 防抖 
  3.  * @param {Function} func 要执行的回调函数 
  4.  * @param {Number} wait 延时的时间 
  5.  * @param {Boolean} immediate 是否立即执行 
  6.  * @return null 
  7.  */ 
  8. let timeout; 
  9. function Debounce(func, wait = 3000, immediate = true) { 
  10.   // 清除定时器 
  11.   if (timeout !== null) clearTimeout(timeout); 
  12.   // 立即执行,此类情况一般用不到 
  13.   if (immediate) { 
  14.     var callNow = !timeout; 
  15.     timeout = setTimeout(function() { 
  16.       timeout = null
  17.     }, wait); 
  18.     if (callNow) typeof func === 'function' && func(); 
  19.   } else { 
  20.     // 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时wait毫秒后执行func回调方法 
  21.     timeout = setTimeout(function() { 
  22.       typeof func === 'function' && func(); 
  23.     }, wait); 
  24.   } 
  25.  
  26. Debounce(()=>console.log(1)); 

递归数组降为一维

  1. let children = [1, [2, 3], [4, [5, 6, [7, 8]]], [9, 10]]; 
  2. function simpleNormalizeChildren(children) { 
  3.             for (let i = 0; i < children.length; i++) { 
  4.                 if (Array.isArray(children[i])) { 
  5.                     children = Array.prototype.concat.apply([], children); 
  6.                     simpleNormalizeChildren(children) 
  7.                 } 
  8.             } 
  9.             return children; 
  10.         } 
  11.  
  12. console.log(simpleNormalizeChildren(children)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

数组降维(二维降一维)

  1. function simpleNormalizeChildren(children) { 
  2.             for (let i = 0; i < children.length; i++) { 
  3.                 if (Array.isArray(children[i])) { 
  4.                     return Array.prototype.concat.apply([], children) 
  5.                 } 
  6.             } 
  7.             return children 
  8. let arrs = [['1'],['3']]; 
  9. const arr = simpleNormalizeChildren(arrs); 
  10. console.log(arr); // ['1','3'

使用可选链进行函数调用

  1. function doSomething(onContent, onError) { 
  2.   try { 
  3.    // ... do something with the data 
  4.   } 
  5.   catch (err) { 
  6.     onError?.(err.message); // 如果onError是undefined也不会有异常 
  7.   } 

检测数组对象中是否有空值

  1. const data = [ 
  2.   { 
  3.    name:"maomin" 
  4.   }, 
  5.   { 
  6.     name:"" 
  7.   } 
  8. const arr = data.filter(item => 
  9.     Object.values(item).includes(''
  10. ); 
  11.  
  12. console.log(arr.length>0?"有空值":"无空值"); // 有空值 

计算数组中每个元素出现的次数

  1. let names = ['Alice''Bob''Tiff''Bruce''Alice']; 
  2.  
  3. let countedNames = names.reduce(function (allNames, name) { 
  4.   if (name in allNames) { 
  5.     allNames[name]++; 
  6.   } 
  7.   else { 
  8.     allNames[name] = 1; 
  9.   } 
  10.   return allNames; 
  11. }, {}); 
  12.  
  13. console.log(countedNames); //  { Alice: 2, Bob: 1, Tiff: 1, Bruce: 1 } 

按属性对object分类

  1. let people = [ 
  2.   { name'Alice', age: 21 }, 
  3.   { name'Max', age: 20 }, 
  4.   { name'Jane', age: 20 } 
  5. ]; 
  6.  
  7. function groupBy(objectArray, property) { 
  8.   return objectArray.reduce(function (acc, obj) { 
  9.     let key = obj[property]; 
  10.     if (!acc[key]) { 
  11.       acc[key] = []; 
  12.     } 
  13.     acc[key].push(obj); 
  14.     return acc; 
  15.   }, {}); 
  16.  
  17. const groupedPeople = groupBy(people, 'age'); 
  18. console.log(groupedPeople); 
  19. // { 
  20. //   20: [ 
  21. //     { name'Max', age: 20 }, 
  22. //     { name'Jane', age: 20 } 
  23. //   ], 
  24. //   21: [{ name'Alice', age: 21 }] 
  25. // } 

将带有分割符的字符串转化成一个n维数组

  1.  const str = "A-2-12"
  2.  const str1 = str.split('-'); 
  3.  console.log(str1); 
  4.  const arr = str1.reverse().reduce((pre,cur,i) => { 
  5.  if(i==0) 
  6.   { pre.push(cur) 
  7.    return pre 
  8.  } 
  9.   return [cur,pre] 
  10. },[]) 
  11.   
  12. console.log(arr) // ["A"["B",["C"]]] 

本文转载自微信公众号「前端历劫之路」,可以通过以下二维码关注。转载本文请联系前端历劫之路公众号。

 

 

责任编辑:武晓燕 来源: 前端历劫之路
相关推荐

2021-07-14 23:57:26

Vue高级技巧

2019-08-20 14:40:35

Redis数据库

2019-11-07 09:20:42

Node.js项目服务器

2021-01-18 11:41:22

SQL数据库编程语言

2021-06-21 09:22:53

按钮设计UI标签

2022-08-09 15:38:55

Linux

2022-04-07 13:02:53

前端缓存

2021-08-04 00:10:49

场景版本大文件

2021-07-09 17:17:09

文件场景内核

2020-10-27 12:06:17

MathJavaScript对象

2018-09-12 15:16:19

数据中心网络机房

2019-12-23 14:04:07

苹果芯片iPhone

2020-08-04 06:32:21

JavaScript代码开发

2019-07-02 10:36:30

JavaScript硬件开发

2020-07-07 07:55:53

web app数据科学机器学习

2018-07-06 15:25:50

程序员编程python

2009-05-18 16:59:42

代码PHP编码

2020-06-10 14:30:45

代码开发AI

2020-08-05 16:09:52

javascript压缩图片前端

2022-10-17 09:01:09

JavaScripNode.js
点赞
收藏

51CTO技术栈公众号