您现在的位置是:首页 > Javascript
当前栏目
今天,学会这10个JS代码段就够了!
2023-03-09 22:03:17 时间
用 apply 将数组各项添加到另一个数组
- const array = ['a', 'b'];
- const elements = [0, 1, 2];
- array.push.apply(array, elements);
- console.info(array); // ["a", "b", 0, 1, 2]
函数只执行一次
- function once (fn){
- let called = false
- return function () {
- if (!called) {
- called = true
- fn.apply(this, arguments)
- }
- }
- }
- function func (){
- console.log(1);
- }
- //调用
- let onlyOnce = once(func);
- // 测试
- onlyOnce(); // 1
- onlyOnce(); // 不执行
防抖
- /**
- * 防抖
- * @param {Function} func 要执行的回调函数
- * @param {Number} wait 延时的时间
- * @param {Boolean} immediate 是否立即执行
- * @return null
- */
- let timeout;
- function Debounce(func, wait = 3000, immediate = true) {
- // 清除定时器
- if (timeout !== null) clearTimeout(timeout);
- // 立即执行,此类情况一般用不到
- if (immediate) {
- var callNow = !timeout;
- timeout = setTimeout(function() {
- timeout = null;
- }, wait);
- if (callNow) typeof func === 'function' && func();
- } else {
- // 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时wait毫秒后执行func回调方法
- timeout = setTimeout(function() {
- typeof func === 'function' && func();
- }, wait);
- }
- }
- Debounce(()=>console.log(1));
递归数组降为一维
- let children = [1, [2, 3], [4, [5, 6, [7, 8]]], [9, 10]];
- function simpleNormalizeChildren(children) {
- for (let i = 0; i < children.length; i++) {
- if (Array.isArray(children[i])) {
- children = Array.prototype.concat.apply([], children);
- simpleNormalizeChildren(children)
- }
- }
- return children;
- }
- console.log(simpleNormalizeChildren(children)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
数组降维(二维降一维)
- function simpleNormalizeChildren(children) {
- for (let i = 0; i < children.length; i++) {
- if (Array.isArray(children[i])) {
- return Array.prototype.concat.apply([], children)
- }
- }
- return children
- }
- let arrs = [['1'],['3']];
- const arr = simpleNormalizeChildren(arrs);
- console.log(arr); // ['1','3']
使用可选链进行函数调用
- function doSomething(onContent, onError) {
- try {
- // ... do something with the data
- }
- catch (err) {
- onError?.(err.message); // 如果onError是undefined也不会有异常
- }
- }
检测数组对象中是否有空值
- const data = [
- {
- name:"maomin"
- },
- {
- name:""
- }
- ]
- const arr = data.filter(item =>
- Object.values(item).includes('')
- );
- console.log(arr.length>0?"有空值":"无空值"); // 有空值
计算数组中每个元素出现的次数
- let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
- let countedNames = names.reduce(function (allNames, name) {
- if (name in allNames) {
- allNames[name]++;
- }
- else {
- allNames[name] = 1;
- }
- return allNames;
- }, {});
- console.log(countedNames); // { Alice: 2, Bob: 1, Tiff: 1, Bruce: 1 }
按属性对object分类
- let people = [
- { name: 'Alice', age: 21 },
- { name: 'Max', age: 20 },
- { name: 'Jane', age: 20 }
- ];
- function groupBy(objectArray, property) {
- return objectArray.reduce(function (acc, obj) {
- let key = obj[property];
- if (!acc[key]) {
- acc[key] = [];
- }
- acc[key].push(obj);
- return acc;
- }, {});
- }
- const groupedPeople = groupBy(people, 'age');
- console.log(groupedPeople);
- // {
- // 20: [
- // { name: 'Max', age: 20 },
- // { name: 'Jane', age: 20 }
- // ],
- // 21: [{ name: 'Alice', age: 21 }]
- // }
将带有分割符的字符串转化成一个n维数组
- const str = "A-2-12";
- const str1 = str.split('-');
- console.log(str1);
- const arr = str1.reverse().reduce((pre,cur,i) => {
- if(i==0)
- { pre.push(cur)
- return pre
- }
- return [cur,pre]
- },[])
- console.log(arr) // ["A"["B",["C"]]]
本文转载自微信公众号「前端历劫之路」,可以通过以下二维码关注。转载本文请联系前端历劫之路公众号。
相关文章
- 乒乒乓乓:这点小事儿,算什么?
- Vue非Node和Vuecli环境开发网站项目-支持动态路由
- 码农属于新生代农民工上热搜 网友:官宣了 没毛病
- 从前序及中序与后序遍历序列构造二叉树登场!
- 令人眼前一亮的 Vue 实战技巧
- Void在JS和TS中的区别
- 7月份Github上JavaScript开源项目排行
- 一篇文章带你搞懂JavaScript 微任务(Microtask)
- 提供可制定化的路由加载方式,Vue 如何做到?
- 聊聊Kubernetes Without Kube-Proxy
- Springboot 中InputStream 神秘消失之谜
- Springboot整合Kafka Stream实时统计数据
- 五分钟带你体验一把分布式事务!so easy!
- 基于JS卡片开发的代码示例工程JsFACard与StepsCard的解析
- 什么?HashMap竟然也有懒加载?
- 如何让 SwiftUI 的列表变得更加灵活
- 设置 CSS 颜色属性的优秀方法是什么
- 盘点Collections类的查找、替换方法的常用方法
- Javascript 中的 CJS、AMD、UMD 和 ESM 是什么?
- 一文弄懂String s="a"+"b"+"c",到底创建了几个对象?