JavaScript
主页 > 网络编程 > JavaScript >

20个拿来就能用的JavaScript技巧分享给大家

2024-02-07 | 佚名 | 点击:

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

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

1

2

3

4

const person = { name: 'Alice', age: 30 };

const { name, age } = person;

console.log(name); // Output: Alice

console.log(age); // Output: 30

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

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

1

2

3

const originalArray = [1, 2, 3];

const clonedArray = [...originalArray];

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

合并对象:

1

2

3

4

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()方法是你转换数据的秘密武器:

1

2

3

const numbers = [1, 2, 3];

const squared = numbers.map(num => num * num);

console.log(squared); // Output: [1, 4, 9]

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

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

1

2

const name = user.name || 'Guest';

console.log(name); // Output: Guest

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

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

1

2

3

4

5

6

function delayedLog(message, time) {

  setTimeout(() => {

    console.log(message);

  }, time);

}

delayedLog('Hello', 1000); // Output (after 1 second): Hello

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

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

1

2

const greet = name => `Hello, ${name}!`;

console.log(greet('Alice')); // Output: Hello, Alice!

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

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

1

2

3

4

5

const promise1 = fetch('url1');

const promise2 = fetch('url2');

Promise.all([promise1, promise2])

  .then(responses => console.log(responses))

  .catch(error => console.error(error));

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

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

1

2

3

const key = 'name';

const person = { [key]: 'Alice' };

console.log(person.name); // Output: Alice

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

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

1

2

3

const name = 'Alice';

const greeting = `Hello, ${name}!`;

console.log(greeting); // Output: Hello, Alice!

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

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

1

2

const notANumber = 'Not a number';

console.log(Number.isNaN(notANumber)); // Output: false

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

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

1

2

const user = { info: { name: 'Alice' } };

console.log(user.info?.age); // Output: undefined

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

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

1

2

3

const text = 'Hello, world!';

const pattern = /Hello/g;

console.log(text.match(pattern)); // Output: ['Hello']

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

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

1

2

3

4

5

6

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():

1

2

3

4

5

6

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简化了处理异步请求:

1

2

3

4

5

6

7

8

9

10

11

async function fetchData() {

  try {

    const response = await fetch('url');

    const data = await response.json();

    console.log(data);

  } catch (error) {

    console.error(error);

  }

}

 

fetchData();

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

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

1

2

3

4

5

6

7

8

9

10

11

function createCounter() {

  let count = 0;

  return function () {

    count++;

    console.log(count);

  };

}

 

const counter = createCounter();

counter(); // Output: 1

counter(); // Output: 2

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

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

1

2

3

4

5

6

7

8

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进行懒加载和滚动动画:

1

2

3

4

5

6

7

8

9

10

11

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模块来编写整洁、模块化的代码:

1

2

3

4

5

6

7

8

// 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:超越对象

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

1

2

3

4

5

6

7

8

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的小窍门和技巧,你已经有了足够的装备,可以将你的编程技能提升到新的水平。

原文链接:
相关文章
最新更新