slot deposit pulsa slot mahjong slot gacor slot gacor slot gacor resmi slot gacor 2025 slot gacor terpercaya slot gacor 2025 slot gacor hari ini slot gacor hari ini slot gacor hari ini
面向每位开发人员的 20 大 JavaScript 技巧和提示
17611538698
webmaster@21cto.com

面向每位开发人员的 20 大 JavaScript 技巧和提示

前端 0 1071 2024-09-27 10:28:37

JavaScript 是一种功能强大且用途广泛的语言,但真正要掌握它是需要付出一定的努力。以下是我收集和工作中常用的20 个 JavaScript 技巧,以便编写更简洁、更高效的代码并改善我的的开发工作流程。希望能够对您们也有所帮助!

1. 使用let和const代替var
避免使用var来声明变量。相反,使用let和const来确保块作用域并避免提升问题。
let name = 'John';const age = 30;

2. 解构赋值

解构允许你将数组中的值或对象的属性提取到不同的变量中

const person = { name: 'Jane', age: 25 };const { name, age } = person;
const numbers = [1, 2, 3];const [first, second] = numbers;

3. 模板字面量

模板文字提供了一种将变量和表达式插入字符串的简单方法

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

4.默认参数

设置函数参数的默认值以避免undefined错误

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

5.箭头函数

箭头函数提供了简洁的语法

const add = (a, b) => a + b;

6. 扩展运算...符

扩展运算符允许您扩展可迭代对象(如数组)的元素或对象的属性。

const arr1 = [1, 2, 3];const arr2 = [...arr1, 4, 5];
const obj1 = { name: 'John' };const obj2 = { ...obj1, age: 30 };

7.剩余 参数

剩余参数允许你将不确定数量的参数表示为一个数组

function sum(...numbers) {  return numbers.reduce((total, num) => total + num, 0);}

8. 短路求值 && 和 ||

对条件表达式和默认值使用短路求值

const user = { name: 'John' };const name = user.name || 'Guest';
const isAdmin = user.isAdmin && 'Admin';

9. 对象属性简写

当属性名称和变量名称相同时,使用简写语法来创建对象

const name = 'John';const age = 30;const person = { name, age };

10. 可选链式?.调用

可选链接允许您安全地访问深度嵌套的属性,而无需检查每个引用是否有效

const user = { name: 'John', address: { city: 'New York' } };const city = user.address?.city;

11. 空值??合并

空值合并 ( ) 提供了一种在左侧操作数为或??时返回右侧操作数的方法

const user = { name: 'John' };const name = user.name ?? 'Guest';

12.数组方法:map()、filter()、reduce()

map()使用、filter()和等数组方法reduce()以函数式方式对数组执行常见操作

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);const evens = numbers.filter(num => num % 2 === 0);const sum = numbers.reduce((total, num) => total + num, 0);

13. Promise 链和 Async/Await

使用 Promises 和 async/await 语法处理异步操作,以获得更干净、更易读的代码

fetch('https://api.example.com/data')  .then(response => response.json())  .then(data => console.log(data))  .catch(error => console.error('Error:', error));

async/await

async function fetchData() {  try {    const response = await fetch('https://api.example.com/data');    const data = await response.json();    console.log(data);  } catch (error) {    console.error('Error:', error);  }}

14. 防抖和节流

通过去抖动和限制频繁调用的函数(例如在滚动或调整大小事件期间)来优化性能

防抖:

function debounce(func, delay) {  let timeoutId;  return function(...args) {    clearTimeout(timeoutId);    timeoutId = setTimeout(() => func.apply(this, args), delay);  };}
window.addEventListener('resize', debounce(() => { console.log('Resized');}, 300));

节流示例:

function throttle(func, limit) {  let inThrottle;  return function(...args) {    if (!inThrottle) {      func.apply(this, args);      inThrottle = true;      setTimeout(() => inThrottle = false, limit);    }  };}
window.addEventListener('scroll', throttle(() => { console.log('Scrolled');}, 300));

15. 使用for...of迭代

使用for...of循环对数组、字符串和其他可迭代对象进行更易读的迭代

const numbers = [1, 2, 3, 4, 5];
for (const number of numbers) { console.log(number);}

16.克隆对象和数组

使用扩展运算符或Object.assign()来克隆对象和数组

const original = { name: 'John', age: 30 };const clone = { ...original };
const arr = [1, 2, 3];const arrClone = [...arr];

17.动态属性名称

使用计算属性名称来动态设置对象属性

const propName = 'age';const person = {  name: 'John',  [propName]: 30};

18. 使用setTimeout和setInterval

setTimeout使用和安排代码执行setInterval

setTimeout(() => {  console.log('This runs after 2 seconds');}, 2000);
const intervalId = setInterval(() => { console.log('This runs every 3 seconds');}, 3000);
// To clear the intervalclearInterval(intervalId);

19. 字符串方法:includes()、startsWith()、endsWith()

使用现代字符串方法执行常见的字符串操作

const str = 'Hello, World!';
console.log(str.includes('World')); // trueconsole.log(str.startsWith('Hello')); // trueconsole.log(str.endsWith('!')); // true

20.console有效使用调试

利用各种console方法进行更有效的调试

console.log('Simple log');console.warn('This is a warning');console.error('This is an error');console.table([{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }]);console.group('Group');console.log('Message 1');console.log('Message 2');console.groupEnd();

评论