返回

JS 宝藏:20+ 令人眼前一亮的前沿技巧

前端

JavaScript 作为一种流行的编程语言,以其灵活性、轻量级和跨平台特性在前端开发领域占据着不可撼动的地位。在日常开发过程中,掌握一些实用的 JavaScript 技巧可以大大提高开发效率,并编写出更健壮的代码。

1. 函数懒加载:

const lazyFunction = () => {
  // 代码块
};

window.addEventListener("load", lazyFunction);

2. 赋值立即执行函数:

const result = (function () {
  // 代码块
  return "结果";
})();

console.log(result); // "结果"

3. 闭包的应用:

const counter = (function () {
  let count = 0;
  return function () {
    return ++count;
  };
})();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

4. 函数结果缓存:

const memoizedFunction = (function () {
  const cache = {};
  return function (n) {
    if (cache[n]) {
      return cache[n];
    } else {
      const result = calculateResult(n);
      cache[n] = result;
      return result;
    }
  };
})();

console.log(memoizedFunction(10)); // 计算结果
console.log(memoizedFunction(10)); // 直接从缓存中获取结果

5. Promise 串行请求:

const makeRequest = (url) => {
  return new Promise((resolve, reject) => {
    // 发送请求并处理结果
  });
};

const urls = ["url1", "url2", "url3"];

urls.reduce((promise, url) => {
  return promise.then(() => makeRequest(url));
}, Promise.resolve()).then(() => {
  // 所有请求完成后的处理逻辑
});

6. 函数柯里化:

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

const add10 = add.bind(null, 10);

console.log(add10(20)); // 30

7. 展开运算符:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArray = [...arr1, ...arr2];

console.log(combinedArray); // [1, 2, 3, 4, 5, 6]

8. 对象解构:

const person = {
  name: "John Doe",
  age: 30,
  city: "New York",
};

const { name, age } = person;

console.log(name); // "John Doe"
console.log(age); // 30

9. 数组解构:

const numbers = [1, 2, 3, 4, 5];

const [first, second, ...rest] = numbers;

console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]

10. 函数默认参数:

const greet = (name = "World") => {
  console.log(`Hello, ${name}!`);
};

greet(); // "Hello, World!"
greet("John Doe"); // "Hello, John Doe!"

11. 模板字符串:

const name = "John Doe";
const age = 30;

const message = `Hello, my name is ${name} and I am ${age} years old.`;

console.log(message); // "Hello, my name is John Doe and I am 30 years old."

12. 箭头函数:

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

const square = n => n * n;

console.log(sum(10, 20)); // 30
console.log(square(5)); // 25

13. 类:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const john = new Person("John Doe", 30);

john.greet(); // "Hello, my name is John Doe and I am 30 years old."

14. 模块:

// module.js
export const add = (a, b) => a + b;

export const square = n => n * n;

// main.js
import { add, square } from "./module.js";

console.log(add(10, 20)); // 30
console.log(square(5)); // 25

15. 异步编程:

const promise = new Promise((resolve, reject) => {
  // 异步操作
  setTimeout(() => {
    resolve("Hello, World!");
  }, 2000);
});

promise.then((result) => {
  console.log(result); // "Hello, World!"
});

16. 事件监听器:

const button = document.getElementById("button");

button.addEventListener("click", () => {
  console.log("Button clicked!");
});

17. DOM 操作:

const element = document.getElementById("element");

element.innerHTML = "Hello, World!";

element.style.color = "red";

18. 定时器:

setTimeout(() => {
  console.log("Hello, World!");
}, 2000);

setInterval(() => {
  console.log("Hello, World!");
}, 2000);

19. 正则表达式:

const regex = /hello/g;

const string = "Hello, World!";

console.log(regex.test(string)); // true

const matches = string.match(regex);

console.log(matches); // ["hello"]

20. JSON:

const person = {
  name: "John Doe",
  age: 30,
};

const json = JSON.stringify(person);

console.log(json); // "{\"name\":\"John Doe\",\"age\":30}"

const object = JSON.parse(json);

console.log(object); // {name: "John Doe", age: 30}

以上技巧仅是冰山一角,JavaScript 还有许多其他有用的技巧和特性。掌握这些技巧可以帮助开发人员编写出更简洁、更健壮、更高效的代码。希望这些技巧能帮助您在 JavaScript 开发中更上一层楼。