JavaScript 以其灵活性和强大的表达能力而闻名,分享一些值得使用的 JavaScript 一行代码解决方案,这些代码简洁优雅却能实现复杂的功能。

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]

数组扁平化

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

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

快速生成数字序列

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

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

2. 字符串处理技巧

生成随机字符串

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

// 示例
console.log(randomString(10)); // "a1b2c3d4e5"

字符串反转

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

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

检查回文字符串

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

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

3. 对象处理大师

深度克隆对象

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

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

合并多个对象

const merge=(...objects)=>({·..objects });

// 示例

const obj1={a:1 };

const obj2={b:2 };

const obj3={c:3};

console.log(merge(obj1,obj2,obj3));//fa:1,b:2,c: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. 函数式编程技巧

函数组合

const compose=(...fns)=>x=> fns.reduceRight((y,f)=>f(y),x);

// 示例

const add0ne=X=> X+ 1;

const double =x=>x*2;

const add0neThenDouble=compose(double,add0ne);

console.log(add0neThenDouble(3));//8

函数柯里化

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. 日期时间处理

格式化日期

const formatDate = date => new Intl,DateTimeFormat('zh-CN').format(date);

// 示例

console.log(formatDate(new Date()));//"2025/2/15"

计算时间差

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 操作技巧

获取所有表单数据

const getFormData= form => 0bject.fromEntries(new FormData(form));

// 示例

document.querySelector('form').addventListener('submit',e => {

    const data=getFormData(e.target);

    console.log(data);

});

平滑滚动到顶部

const scrollToTop=()=> window.scrollTo({ top:0,behavior:smooth'});

// 示例

document.getElementById('topButton').onclick = scrollToTop;

7. 实用工具函数

防抖函数

const debounce =(fn,delay)=>{

    let timer;

    return (...args)=>{

        clearTimeout(timer);

        timer=setTimeout(()=>fn(...args),delay);

    };

};

// 示例

const debouncedSearch=debounce(searchFunction,300);


节流函数

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);