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

2023年 10月 18日 27.7k 0

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

相关文章

如何删除WordPress中的所有评论
检查WordPress服务器磁盘使用情况的7种简便方法(查找大文件和数据)
如何更改WordPress常量FS_METHOD
如何为区块编辑器、Elementor等构建WordPress文章模板
如何彻底地删除WordPress主题及相关内容
如何使用WordPress搭建一个内网

发布评论