【好用的数据处理方法】

1. 数组操作神器

1.1 数组去重

const unique = arr => [...new Set(arr)];

// 示例
const numbers = [1, 2, 2, 3, 3, 4, 5, 5];
console.log(unique(numbers)); // [1, 2, 3, 4, 5]

1.2 数组扁平化

const flatten = arr => arr.flat(Infinity);

// 示例
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(flatten(nested)); // [1, 2, 3, 4, 5, 6]

1.3 快速生成数字序列

const range = (start, end) => [...Array(end - start + 1)].map((_, i) => start + i);

// 示例
console.log(range(1, 5)); // [1, 2, 3, 4, 5]

2. 字符串处理技巧

2.1 生成随机字符串

const randomString = length => Math.random().toString(36).substring(2, length + 2);

// 示例

2.2 字符串反转

const reverse = str => str.split('').reverse().join('');

// 示例
console.log(reverse('hello')); // "olleh"

2.3 检查回文字符串

const isPalindrome = str => str === str.split('').reverse().join('');

// 示例
console.log(isPalindrome('radar')); // true
console.log(isPalindrome('hello')); // false

3. 对象处理大师

3.1 深度克隆对象

const deepClone = obj => JSON.parse(JSON.stringify(obj));

// 示例
const original = { a: 1, b: { c: 2 } };
const clone = deepClone(original);

3.2 合并多个对象

const merge=(...objects)=>({·..objects });
/1 示例
const obj1={a:1 };const obj2={b:2 };
const obj3={c:3};console.log(merge(obj1,obj2,obj3));//fa:1,b:2,c:3}

3.3 提取对象字段

const pick =(obj,keys)=> keys.reduce((acc,key)=>((acc[key]= obj[key]),acc), {});
// 示例
const user={name:'张三,age:30,email:'zhang@example.com'};
console.log(pick(user,'name''email']));//{name:'张=',email:'zhang@example.com'}

4. 函数式编程技巧

4.1 函数组合

const compose=(...fns)=>x=> fns.reduceRight((y,f)=>f(y),x);
/1 示例
const addone=X=> X+ 1;
const double =x=>x*2;
const addOneThenDouble=compose(double,add0ne);
console.log(addoneThenDouble(3));//8

4.2 函数柯里化

const curry
=fn =>(...args)=>args.length >= fn.length ?fn(...args):(...more)=>
curry(fn)(...args,
..more);
示例
const add=(a,b,c)=>a+b+C;
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3));//6

5. 日期时间处理

5.1 格式化日期

const formatDate = date => new Intl.DateTimeFormat('zh-CN').format(date);
/1 示例
console.log(formatDate(new Date()));//"2025/2/15"

5.2 计算时间差

const timeDiff = (date1,date2)=>Math.abs(date1-date2)/(1000*60 *60 * 24);
// 示例
const date1= new Date('2025-01-01');
const date2 =new Date('2025-02-01');
console.log(timeDiff(date1,date2));//31

6.DOM 操作技巧

6.1 获取所有表单数据

const getFormData= form => 0bject.fromEntries(new FormData(form));
/1 示例
document.querySelector('form').addventListener('submit',e => {
	const data=getFormData(e.target);
	console.log(data);
});

6.2 平滑滚动到顶部

const scrollToTop=()=> window.scrollTo({ top:0,behavior:smooth'});
// 示例
document.getElementById('topButton').onclick = scrollToTop;

7. 实用工具函数

7.1 防抖函数

const debounce =(fn,delay)=>{let timer;return(...args)=>{clearTimeout(timer);timer=setTimeout(()=>fn(...args),delay);
};
// 示例
const debouncedSearch=debounce(searchFunction,300);

7.2 节流函数

const throttle = (fn, delay) => {
    let last = 0;
    return (...args) => {
        const now = Date.now();
        if (now - last >= delay) {
            fn(...args);
            last = now;
        }
    };
};

// 示例
const throttledScroll = throttle(handleScroll, 100);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值