现在就可以使用的 20 个 JavaScript 技巧和窍门

开发 前端
今天探讨 20 种 JavaScript 技巧和窍门,每种技巧和窍门都有通俗易懂的示例。让我们一起来提升你的 JavaScript 技能吧!

1、解构魔法:轻松提取值

解构允许你轻松地从数组或对象中解包值。以下是一个例子:

const person = { name: 'Alice’, age: 30 };
const { name, age } = person;
console.log(name); // Output: Alice
console.log(age); // Output: 30

2、展开运算:克隆数组和合并对象

扩展运算符(...)让你能轻松地创建数组的副本并合并对象:

const originalArray = [1, 2, 3];
const clonedArray = [...originalArray];
console.log(clonedArray); // Output: [1, 2, 3]

合并对象:

const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = { ...obj1, ...obj2 };
console.log(merged); // Output: { a: 1, b: 3, c: 4 }

3、map() 轻松实现转换

map()方法是你转换数据的秘密武器:

const numbers = [1, 2, 3];
const squared = numbers.map(num => num * num);
console.log(squared); // Output: [1, 4, 9]

4、 && 和 || 的短路操作:优雅的条件判断

使用 && 和 || 来创建清晰简洁的条件语句:

const name = user.name || 'Guest';
console.log(name); // Output: Guest

5、串联 setTimeout():延迟序列化

将setTimeout()链接起来可以创建一系列的延迟操作:

function delayedLog(message, time) {
  setTimeout(() => {
    console.log(message);
  }, time);
}
delayedLog('Hello', 1000); // Output (after 1 second): Hello

6、箭头函数:简洁而强大

箭头函数(() => {})不仅简洁,而且还保留了this的值:

const greet = name => `Hello, ${name}!`;
console.log(greet(’Alice’)); // Output: Hello, Alice!

7、掌握 Promise.all():处理多个 Promise

使用 Promise.all() 来合并多个承诺并集体处理它们:

const promise1 = fetch('url1');
const promise2 = fetch('url2');
Promise.all([promise1, promise2])
  .then(responses => console.log(responses))
  .catch(error => console.error(error));

8、动态属性名称:多功能对象键

可以使用方括号将变量用作对象属性名称:

const key = 'name';
const person = { [key]: 'Alice' };
console.log(person.name); // Output: Alice

9、模板字面量魔法:字符串格式化

模板字面量 (${}) 允许你在字符串中嵌入表达式:

const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Alice!

10、NaN 检查:更安全的替代方案

使用 Number.isNaN() 来准确地检查一个值是否为 NaN:

const notANumber = 'Not a number';
console.log(Number.isNaN(notANumber)); // Output: false

11、可选链(?.):驯服未定义的值

在处理嵌套属性时,通过可选链来避免错误:

const user = { info: { name: 'Alice' } };
console.log(user.info?.age); // Output: undefined

12、正则表达式复兴:掌握模式

正则表达式(RegExp)是用于模式匹配的强大工具:

const text = 'Hello, world!';
const pattern = /Hello/g;
console.log(text.match(pattern)); // Output: ['Hello']

13、JSON.parse() reviver:转换解析数据

在JSON.parse()中的reviver参数允许你转换解析后的JSON:

const data = '{"age":"30"}';
const parsed = JSON.parse(data, (key, value) => {
  if (key === 'age') return Number(value);
  return value;
});
console.log(parsed.age); // Output: 30

14. 酷炫控制台技巧:调试的乐趣

使用console.table()和console.groupCollapsed()超越console.log():

const users = [{ name: 'Alice' }, { name: 'Bob' }];
console.table(users);
console.groupCollapsed(’Details’);
console.log(’Name: Alice’);
console.log(’Age: 30’);
console.groupEnd();

15、使用async/await获取:异步简易性

使用fetch()的async/await简化了处理异步请求:

async function fetchData() {
  try {
    const response = await fetch('url');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

fetchData();

16、无拘无束的闭包:数据隐私

闭包让你在函数中创建私有变量:

function createCounter() {
  let count = 0;
  return function () {
    count++;
    console.log(count);
  };
}

const counter = createCounter();
counter(); // Output: 1
counter(); // Output: 2

17、提高速度的缓存:高效重新计算

备忘录化通过缓存函数结果来提高性能:

function fibonacci(n, memo = {}) {
  if (n in memo) return memo[n];
  if (n <= 2) return 1;
  memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
  return memo[n];
}

console.log(fibonacci(10)); // Output: 55

18、IntersectionObserver:轻松的滚动效果

使用 Intersection Observer 者API进行懒加载和滚动动画:

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add('fade-in');
      observer.unobserve(entry.target);
    }
  });
});

const elements = document.querySelectorAll('.animate');
elements.forEach(element => observer.observe(element));

19、清晰代码的ES6模块:有组织且模块化

使用ES6模块来编写整洁、模块化的代码:

// math.js
export function add(a, b) {
  return a + b;
}

// app.js
import { add } from './math.js';
console.log(add(2, 3)); // Output: 5

20、Proxy:超越对象

代理允许你拦截并自定义对象操作:

const handler = {
  get(target, prop) {
    return `Property "${prop}" doesn't exist.`;
  }
};

const proxy = new Proxy({}, handler);
console.log(proxy.name); // Output: Property "name" doesn’t exist.

配备了这20个JavaScript的小窍门和技巧,你已经有了足够的装备,可以将你的编程技能提升到新的水平。

责任编辑:姜华 来源: 大迁世界
相关推荐

2020-08-04 06:32:21

JavaScript代码开发

2021-01-09 09:23:29

CSS页面渲染开发

2013-12-31 09:26:31

JavaScript技巧

2009-03-17 08:46:57

Windows 7微软发布

2020-07-06 10:55:38

CIO首席信息官IT

2021-04-13 10:20:13

Edge Canary浏览器微软

2022-10-17 07:16:08

SQL机器学习AI

2018-04-28 09:10:01

微软OfficeWindows

2021-12-27 08:21:24

微信微信小技巧移动应用

2017-02-13 09:33:32

2022-03-01 15:26:29

漏洞网络攻击

2021-11-14 15:48:42

Windows 11Windows微软

2021-01-31 23:56:49

JavaScript开发代码

2018-04-19 14:30:25

LinuxVi编辑器

2009-12-17 09:09:48

Windows 7系统分区

2009-10-21 09:46:13

VB使用ArrayLi

2022-02-28 17:57:44

云迁移云计算

2018-11-27 09:21:41

负载均衡机器Session

2022-02-28 22:58:04

云迁移IT开发

2020-07-15 08:00:52

Rust语言技巧
点赞
收藏

51CTO技术栈公众号