15 个 JavaScript 技巧和提示

329 阅读2分钟

15 个 JavaScript 技巧和提示

1. 空值合并运算符 (??)

  • 使用场景:当左操作数为 nullundefined 时,使用 ?? 赋予默认值。

    示例

  const username = user.name ?? '访客';
  console.log(username); // 如果 user.name 为 null 或 undefined,输出:'访客'

2. 可选链运算符 (?.)

  • 使用场景:在访问深层嵌套的属性时,无需检查每一层级。

    示例

  const address = user?.contact?.address?.city;
  console.log(address); // 如果属性缺失,避免运行时错误

这确保即使 user 对象中缺少 contactaddress 属性,代码也不会抛出错误。

3. 模板字面量

  • 使用场景:简化字符串插值和多行字符串。

    示例

  const username = "saurabh";
  const entries = 1567;
  const message = `你好,${username}!欢迎来到仪表板,你还有 ${entries} 条记录。`;

4. 默认参数

  • 使用场景:为函数参数指定默认值。

    示例

  function greet(name = '访客') {
      console.log(`你好,${name}!`);
  }

5. 数组展开运算符 (...)

  • 使用场景:轻松克隆或合并数组。

    示例

  const newArray = [...array1, ...array2];

6. 数组过滤

  • 使用场景:根据条件提取元素。

    示例

  const adults = users.filter(user => user.age >= 18);

上述代码将所有年龄大于或等于 18 的用户过滤到新的数组 adults 中。

7. 数组映射

  • 使用场景:转换数组元素。

    示例

  const names = users.map(user => user.name);

数组 names 将包含所有用户的姓名。

8. 防抖

  • 使用场景:限制函数的执行频率。

    示例

  const debounce = (func, delay) => {
    let timeout;
    return (...args) => {
      clearTimeout(timeout);
      timeout = setTimeout(() => func(...args), delay);
    };
  };

9. 节流

  • 使用场景:控制函数在一段时间内的执行次数。

    示例

  const throttle = (func, limit) => {
    let lastFunc;
    let lastRan;
    return (...args) => {
      if (!lastRan) {
        func(...args);
        lastRan = Date.now();
      } else {
        clearTimeout(lastFunc);
        lastFunc = setTimeout(() => {
          if (Date.now() - lastRan >= limit) {
            func(...args);
            lastRan = Date.now();
          }
        }, limit - (Date.now() - lastRan));
      }
    };
  };

10. Promise.all

  • 使用场景:并行处理多个 Promise。

    示例

  const results = await Promise.all([fetchData1(), fetchData2()]);

11. 记忆化

  • 使用场景:缓存函数结果,以加速重复调用。

    示例

  const memoize = fn => {
    const cache = {};
    return (...args) => {
      const key = JSON.stringify(args);
      if (!cache[key]) cache[key] = fn(...args);
      return cache[key];
    };
  };

12. 字符串方法

  • 使用场景:使用 startsWithendsWithincludes 等方法检查字符串。

    示例

  if (str.startsWith('Hello')) console.log('检测到问候语');

13. 数字方法

  • 使用场景:安全地转换数字。

    示例

  const num = Number.parseInt('42', 10);

14. Intl 格式化

  • 提示:使用 Intl 进行货币、日期和数字格式化。

    示例

  const formatter = new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' });
  console.log(formatter.format(1000)); // ¥1,000.00

15. Set

  • 使用场景:存储唯一值。

    示例

  const unique = new Set([1, 2, 3, 1]);
unique` 将包含 `[1, 2, 3]`,因为