返回

让JavaScript代码发挥妙用:工具函数大集合,助力开发更高效

前端

前言
在JavaScript开发过程中,我们经常会遇到各种各样的任务,比如数组去重、关键词高亮、打乱数组等。这些操作往往需要我们编写大量的代码,但其实,JavaScript中有很多内置的工具函数可以帮助我们轻松完成这些任务。

本文将介绍一些常用的JavaScript工具函数,涵盖数组操作、字符串处理、对象操作、函数扩展、日期处理和事件处理等方面。通过这些工具函数,我们可以极大地提高代码的效率和可读性。

数组操作

1. 数组去重

JavaScript中,数组去重是一个常见的需求。我们可以使用Array.prototype.filter()方法来实现数组去重。如下所示:

const arr = [1, 2, 3, 4, 5, 1, 2, 3];
const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(uniqueArr); // [1, 2, 3, 4, 5]

2. 数组打乱

数组打乱也是一个常见需求。我们可以使用Array.prototype.sort()方法来实现数组打乱。如下所示:

const arr = [1, 2, 3, 4, 5];
arr.sort(() => Math.random() - 0.5);
console.log(arr); // [3, 5, 2, 1, 4]

3. 数组交集

数组交集是指两个数组中同时存在的元素。我们可以使用Array.prototype.filter()方法来实现数组交集。如下所示:

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];
const intersection = arr1.filter((item) => arr2.includes(item));
console.log(intersection); // [3, 4, 5]

4. 数组差集

数组差集是指在一个数组中存在,而在另一个数组中不存在的元素。我们可以使用Array.prototype.filter()方法来实现数组差集。如下所示:

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];
const difference = arr1.filter((item) => !arr2.includes(item));
console.log(difference); // [1, 2]

字符串处理

1. 字符串首字母大写

字符串首字母大写是一个常见需求。我们可以使用String.prototype.charAt()String.prototype.toUpperCase()方法来实现字符串首字母大写。如下所示:

const str = "hello world";
const capitalizedStr = str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalizedStr); // "Hello world"

2. 字符串尾部添加字符

字符串尾部添加字符是一个常见需求。我们可以使用String.prototype.concat()方法来实现字符串尾部添加字符。如下所示:

const str = "hello";
const newStr = str.concat(" world");
console.log(newStr); // "hello world"

3. 字符串查找

字符串查找是一个常见需求。我们可以使用String.prototype.indexOf()String.prototype.lastIndexOf()方法来实现字符串查找。如下所示:

const str = "hello world";
const index = str.indexOf("world");
const lastIndex = str.lastIndexOf("world");
console.log(index); // 6
console.log(lastIndex); // 6

4. 字符串替换

字符串替换是一个常见需求。我们可以使用String.prototype.replace()方法来实现字符串替换。如下所示:

const str = "hello world";
const newStr = str.replace("world", "universe");
console.log(newStr); // "hello universe"

对象操作

1. 对象克隆

对象克隆是一个常见需求。我们可以使用Object.assign()方法来实现对象克隆。如下所示:

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

const clonedObj = Object.assign({}, obj);
console.log(clonedObj); // { name: "John", age: 30, city: "New York" }

2. 对象合并

对象合并是一个常见需求。我们可以使用Object.assign()方法来实现对象合并。如下所示:

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

const obj2 = {
  city: "New York",
  country: "USA",
};

const mergedObj = Object.assign({}, obj1, obj2);
console.log(mergedObj); // { name: "John", age: 30, city: "New York", country: "USA" }

3. 对象遍历

对象遍历是一个常见需求。我们可以使用Object.keys()Object.values()方法来实现对象遍历。如下所示:

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

for (const key of Object.keys(obj)) {
  console.log(key); // "name", "age", "city"
}

for (const value of Object.values(obj)) {
  console.log(value); // "John", "30", "New York"
}

4. 对象删除属性

对象删除属性是一个常见需求。我们可以使用delete操作符来实现对象删除属性。如下所示:

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

delete obj.age;
console.log(obj); // { name: "John", city: "New York" }

函数扩展

1. 函数柯里化

函数柯里化是指将一个函数拆分成多个函数,其中每个函数都接受一个参数。函数柯里化可以帮助我们编写出更灵活和可重用的代码。如下所示:

function add(a, b, c) {
  return a + b + c;
}

const addCurried = a => b => c => a + b + c;

const add10 = addCurried(10);
const add10And20 = add10(20);
const result = add10And20(30);
console.log(result); // 60

2. 函数节流

函数节流是指在一定时间内只允许函数执行一次。函数节流可以帮助我们防止函数被频繁调用,从而提高代码的性能。如下所示:

function throttle(func, wait) {
  let timer = null;
  return function (...args) {
    if (timer) {
      return;
    }
    timer = setTimeout(() => {
      func.apply(this, args);
      timer = null;
    }, wait);
  };
}

const handleClick = () => {
  console.log("Button clicked");
};

const throttledHandleClick = throttle(handleClick, 1000);

document.getElementById("btn").addEventListener("click", throttledHandleClick);

3. 函数去抖动

函数去抖动是指在一定时间内只允许函数执行一次。函数去抖动可以帮助我们防止函数被频繁调用,从而提高代码的性能。如下所示:

function debounce(func, wait) {
  let timer = null;
  return function (...args) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      func.apply(this, args);
      timer = null;
    }, wait);
  };
}

const handleInput = () => {
  console.log("Input value changed");
};

const debouncedHandleInput = debounce(handleInput, 500);

document.getElementById("input").addEventListener("input", debouncedHandleInput);

日期处理

1. 获取当前日期

获取当前日期是一个常见需求。我们可以使用Date.now()