专业编程教程与实战项目分享平台

网站首页 > 技术文章 正文

50个常用的JavaScript技巧汇总_javascript是什么功能

ins518 2025-10-13 22:12:40 技术文章 1 ℃ 0 评论

以下是 50 个常用的 JavaScript 技巧,涵盖变量处理、数组操作、对象处理、函数优化、异步编程等多个场景,附带简洁示例:

1. 变量交换(无需临时变量)

let a = 1, b = 2;
[a, b] = [b, a]; // a=2, b=1

2. 解构赋值简化对象 / 数组访问

// 对象解构
const { name, age } = { name: 'Alice', age: 20 };

// 数组解构
const [first, second] = [10, 20, 30]; // first=10, second=20

// 嵌套解构
const { user: { id } } = { user: { id: 1, name: 'Bob' } };

3. 数组去重(Set)

const arr = [1, 2, 2, 3, 3, 3];
const uniqueArr = [...new Set(arr)]; // [1,2,3]

4. 短路求值简化条件判断

// 当a为真时使用a,否则使用默认值
const result = a || 'default';

// 当a为真时执行函数
a && doSomething();

5. 可选链操作符(?.)避免报错

// 安全访问深层属性,避免Cannot read property 'x' of undefined
const username = user?.info?.name;

// 安全调用函数
const data = api.fetch?.(); // 若fetch不存在则返回undefined

6. 空值合并运算符(??)处理默认值

// 仅当左侧为null/undefined时使用右侧(区别于||,0和''不会被覆盖)
const score = 0 ?? 100; // 0(若用||会返回100)
const name = '' ?? 'Guest'; // ''(若用||会返回'Guest')

7. 快速生成数组(Array.from)

// 生成1-10的数组
const nums = Array.from({ length: 10 }, (_, i) => i + 1); // [1,2,...,10]

8. 数组扁平化(flat/flatMap)

const nestedArr = [1, [2, [3]]];
const flatArr = nestedArr.flat(2); // 扁平2层:[1,2,3]

// 先映射再扁平(常用)
const arr = [1, 2, 3];
const mapped = arr.flatMap(x => [x, x*2]); // [1,2, 2,4, 3,6]

9. 函数参数默认值

function greet(name = 'Guest') {
  return `Hello, ${name}!`;
}
greet(); // "Hello, Guest!"

10. 剩余参数(...)收集不定参数

function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6

11. 展开运算符(...)复制 / 合并

// 复制数组(避免引用)
const arrCopy = [...arr];

// 合并数组
const merged = [...arr1, ...arr2];

// 复制对象
const objCopy = { ...obj };

// 合并对象(后面对象覆盖前面)
const mergedObj = { ...obj1, ...obj2 };

12. 数字转字符串(隐式转换)

const num = 123;
const str = num + ''; // "123"

13. 字符串转数字(隐式转换)

const str = "123";
const num = +str; // 123(比parseInt更简洁)

14. 取整(替代 Math.floor/Math.ceil)

const num = 3.7;
const floor = ~~num; // 3(等效Math.floor,仅对32位整数有效)
const ceil = -~num; // 4(等效Math.ceil)

15. 随机数(指定范围)

// 生成[min, max]之间的随机整数
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

16. 检查数组是否包含元素(includes)

const arr = [1, 2, 3];
arr.includes(2); // true
arr.includes(4); // false

17. 对象属性存在性检查(hasOwnProperty)

const obj = { name: 'Alice' };
obj.hasOwnProperty('name'); // true
obj.hasOwnProperty('age'); // false

18. 数组查找元素(find/findIndex)

const users = [{ id: 1 }, { id: 2 }];
const user = users.find(u => u.id === 2); // {id:2}
const index = users.findIndex(u => u.id === 2); // 1

19. 过滤数组(filter)

const numbers = [1, 2, 3, 4];
const evens = numbers.filter(n => n % 2 === 0); // [2,4]

20. 数组排序(sort)

// 数字排序(避免默认字符串排序)
const nums = [3, 1, 4];
nums.sort((a, b) => a - b); // [1,3,4](升序)
nums.sort((a, b) => b - a); // [4,3,1](降序)

21. 防抖(Debounce)

// 频繁触发时,仅最后一次触发后延迟执行
function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}
// 用法:输入框搜索防抖
input.addEventListener('input', debounce(search, 300));

22. 节流(Throttle)

// 一段时间内仅执行一次
function throttle(fn, interval) {
  let lastTime = 0;
  return (...args) => {
    const now = Date.now();
    if (now - lastTime >= interval) {
      fn.apply(this, args);
      lastTime = now;
    }
  };
}
// 用法:滚动事件节流
window.addEventListener('scroll', throttle(handleScroll, 100));

23. 深拷贝(JSON 方法,简单场景)

const obj = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(obj)); // 注意:不支持函数、RegExp等

24. 数组清空

const arr = [1, 2, 3];
arr.length = 0; // arr变为[]

25. 快速创建对象(简洁语法)

const name = 'Alice';
const age = 20;
// 键名与变量名相同时可简写
const user = { name, age }; // {name: 'Alice', age: 20}

26. 对象方法简写

const obj = {
  // 省略function关键字
  greet() { 
    return 'Hello'; 
  }
};

27. 动态对象属性

const key = 'name';
const obj = {
  [key]: 'Alice' // 等价于 { name: 'Alice' }
};

28. 获取对象键 / 值 / 键值对

const obj = { a: 1, b: 2 };
Object.keys(obj); // ['a', 'b']
Object.values(obj); // [1, 2]
Object.entries(obj); // [['a',1], ['b',2]]

29. 箭头函数简化回调

// 替代传统function
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2); // [2,4,6]

30. 立即执行函数(IIFE)

// 隔离作用域,避免污染全局
(function() {
  const msg = 'Hello';
  console.log(msg);
})();

31. Promise 简化异步

// 封装异步操作
function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve('Data'), 1000);
  });
}
// 使用
fetchData().then(data => console.log(data));

32. async/await 更优雅处理异步

async function getData() {
  try {
    const data = await fetchData(); // 等待Promise完成
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

33. Promise.all 处理并行异步

// 等待所有Promise完成
const promises = [fetch('/a'), fetch('/b')];
const results = await Promise.all(promises);

34. Promise.race 取最快完成的异步

// 仅等待第一个完成的Promise
const fastest = await Promise.race([fetch('/a'), fetch('/b')]);

35. 数组判断(Array.isArray)

Array.isArray([]); // true
Array.isArray({}); // false

36. 字符串重复(repeat)

'Hi'.repeat(3); // "HiHiHi"

37. 字符串首尾去空格(trim)

'  Hello  '.trim(); // "Hello"
'  Hello  '.trimStart(); // "Hello  "(仅去开头)
'  Hello  '.trimEnd(); // "  Hello"(仅去结尾)

38. 条件添加对象属性

const obj = {
  name: 'Alice',
  ...(isAdmin && { role: 'admin' }) // 仅当isAdmin为true时添加role
};

39. 数组条件过滤 + 映射(链式调用)

const numbers = [1, 2, 3, 4, 5];
const result = numbers
  .filter(n => n > 2) // [3,4,5]
  .map(n => n * 2); // [6,8,10]

40. 事件委托(减少事件监听)

// 给父元素添加一次监听,处理所有子元素事件
ul.addEventListener('click', (e) => {
  if (e.target.tagName === 'LI') {
    console.log('点击了列表项', e.target);
  }
});

41. 数组求和(reduce)

const nums = [1, 2, 3];
const sum = nums.reduce((total, num) => total + num, 0); // 6

42. 数组最大值 / 最小值

const nums = [1, 5, 3];
const max = Math.max(...nums); // 5
const min = Math.min(...nums); // 1

43. 检查变量是否为 null/undefined

const isNil = (value) => value === null || value === undefined;
isNil(null); // true
isNil(undefined); // true
isNil(0); // false

44. 函数柯里化(分步传参)

const add = a => b => a + b;
const add2 = add(2);
add2(3); // 5

45. 日期格式化(简单示例)

const formatDate = (date = new Date()) => {
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};
formatDate(); // "2023-10-05"(示例)

46. 合并多个数组(concat)

const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = arr1.concat(arr2); // [1,2,3,4](等价于[...arr1, ...arr2])

47. 数组判断是否所有元素满足条件(every)

const nums = [2, 4, 6];
const allEven = nums.every(n => n % 2 === 0); // true

48. 数组判断是否有元素满足条件(some)

const nums = [1, 3, 5, 6];
const hasEven = nums.some(n => n % 2 === 0); // true

49. 字符串包含子串(includes/startsWith/endsWith)

const str = 'Hello World';
str.includes('World'); // true
str.startsWith('Hello'); // true
str.endsWith('d'); // true

50. 使用 Map/Set 优化查找性能

// Map查找比对象快(尤其键为非字符串时)
const map = new Map();
map.set('name', 'Alice');
map.get('name'); // "Alice"

// Set查找元素是否存在比数组includes快
const set = new Set([1, 2, 3]);
set.has(2); // true(O(1)复杂度,数组includes是O(n))

这些技巧覆盖了日常开发中 80% 以上的场景,合理运用能显著提升代码简洁性和效率。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表