发布于 2026-01-06 4 阅读
0

37 个用于字符串、对象、数组和日期的 JavaScript 实用函数

37 个用于字符串、对象、数组和日期的 JavaScript 实用函数

查看原文,即可阅读目录。

仅需 49 美元/年即可通过完整的 React Bootcamp学习 React (免费试用 1 个月) *推广链接


实用函数就像代码的快捷方式。它们让你无需编写大量额外代码即可处理数组、日期和字符串等对象。与其一遍又一遍地重复执行相同的任务,不如使用这些函数来更快、更一致地完成工作,并避免错误。

本文将介绍 37 个每个开发者都应该掌握的常用 JavaScript 实用函数。如果您是 JavaScript 新手,或者还没有编写过实用函数的文档,那么本文正适合您。通过学习和使用这些实用函数,您可以节省时间、减少错误,并更深入地了解如何编写简洁、可复用的代码。

相关文章

  1. 你可能不知道的 20 个鲜为人知的 JavaScript 特性
  2. JavaScript 数组/对象构造详解

那么,让我们开始吧,看看这些实用工具如何让你的 JavaScript 编码更轻松、更高效。

JavaScript 中的常用字符串工具

1. 资本化

将字符串的首字母大写。

function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

// Example usage
console.log(capitalize('hello')); // 'Hello'
Enter fullscreen mode Exit fullscreen mode

2. 转换为驼峰式命名法

将带有连字符的字符串转换为驼峰式命名法(camelCase)。

function toCamelCase(input) {
    return (
        input
            // Replace kebab-case, snake_case, and spaces with a space
            .replace(/[-_\s]+(.)?/g, (_, char) => (char ? char.toUpperCase() : ''))
            // Handle PascalCase
            .replace(/^[A-Z]/, (char) => char.toLowerCase())
    );
}

// Test cases
console.log(toCamelCase('PascalCase')); // pascalCase
console.log(toCamelCase('kebab-case-string')); // kebabCaseString
console.log(toCamelCase('snake_case_string')); // snakeCaseString
console.log(toCamelCase('string with spaces')); // stringWithSpaces
Enter fullscreen mode Exit fullscreen mode

3. 转换为烤肉串大小写

将字符串转换为 kebab-case 格式。

function toKebabCase(input) {
    return (
        input
            // Handle camelCase and PascalCase by inserting a dash before uppercase letters
            .replace(/([a-z])([A-Z])/g, '$1-$2')
            // Replace underscores and spaces with dashes
            .replace(/[_\s]+/g, '-')
            // Convert the entire string to lowercase
            .toLowerCase()
    );
}

// Test cases
console.log(toKebabCase('camelCase')); // camel-case
console.log(toKebabCase('PascalCase')); // pascal-case
console.log(toKebabCase('snake_case_string')); // snake-case-string
console.log(toKebabCase('string with spaces')); // string-with-spaces
Enter fullscreen mode Exit fullscreen mode

4. 转换为蛇形外壳

将字符串转换为蛇形命名法(snake_case)。

function toSnakeCase(input) {
    return (
        input
            // Handle camelCase and PascalCase by inserting an underscore before uppercase letters
            .replace(/([a-z])([A-Z])/g, '$1_$2')
            // Replace dashes and spaces with underscores
            .replace(/[-\s]+/g, '_')
            // Convert the entire string to lowercase
            .toLowerCase()
    );
}

// Test cases
console.log(toSnakeCase('camelCase')); // camel_case
console.log(toSnakeCase('PascalCase')); // pascal_case
console.log(toSnakeCase('kebab-case-string')); // kebab_case_string
console.log(toSnakeCase('string with spaces')); // string_with_spaces
Enter fullscreen mode Exit fullscreen mode

5. 转换为 Pascal 命名法

将字符串转换为 PascalCase 格式。

function toPascalCase(input) {
    return (
        input
            // Replace camelCase, kebab-case, snake_case, and spaces with a space
            .replace(/([a-z])([A-Z])|[-_\s]+(.)?/g, (match, p1, p2, p3) => {
                if (p2) {
                    return p1 + ' ' + p2;
                }
                return p3 ? ' ' + p3.toUpperCase() : '';
            })
            // Split by space, capitalize first letter of each word, and join
            .split(' ')
            .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
            .join('')
    );
}

// Test cases
console.log(toPascalCase('camelCase')); // CamelCase
console.log(toPascalCase('kebab-case-string')); // KebabCaseString
console.log(toPascalCase('snake_case_string')); // SnakeCaseString
console.log(toPascalCase('string with spaces')); // StringWithSpaces
Enter fullscreen mode Exit fullscreen mode

6. 检查字符串是否包含另一个字符串

检查字符串是否包含指定的子字符串。

function contains(str, substring) {
    return str.indexOf(substring) !== -1;
}

// Example usage
console.log(contains('Hello World', 'World')); // true
Enter fullscreen mode Exit fullscreen mode

7. 替换所有出现的位置

替换字符串中所有出现的子字符串。

function replaceAll(str, find, replace) {
    return str.split(find).join(replace);
}

// Example usage
console.log(replaceAll('Hello World', 'o', 'a')); // 'Hella Warld'
Enter fullscreen mode Exit fullscreen mode

8. 统计字符出现的次数

统计字符串中某个字符出现的次数。

function countOccurrences(str, char) {
    return str.split(char).length - 1;
}

// Example usage
console.log(countOccurrences('Hello World', 'o')); // 2
Enter fullscreen mode Exit fullscreen mode

9. 转义 HTML

对 HTML 特殊字符进行转义,以防止 XSS 攻击。

function escapeHTML(str) {
    return str.replace(/[&<>"']/g, function (match) {
        const escapeChars = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        };
        return escapeChars[match];
    });
}

// Example usage
console.log(escapeHTML('<div>"Hello" & \'World\'</div>'));
// '&lt;div&gt;&quot;Hello&quot; &amp; &#39;World&#39;&lt;/div&gt;'
Enter fullscreen mode Exit fullscreen mode

10. 取消 HTML 转义

对 HTML 特殊字符进行转义。

function unescapeHTML(str) {
    return str.replace(/&amp;|&lt;|&gt;|&quot;|&#39;/g, function (match) {
        const unescapeChars = {
            '&amp;': '&',
            '&lt;': '<',
            '&gt;': '>',
            '&quot;': '"',
            '&#39;': "'"
        };
        return unescapeChars[match];
    });
}

// Example usage
console.log(unescapeHTML('&lt;div&gt;&quot;Hello&quot; &amp; &#39;World&#39;&lt;/div&gt;'));
// '<div>"Hello" & \'World\'</div>'
Enter fullscreen mode Exit fullscreen mode

11. 货币格式

将数字格式化为货币字符串,以逗号作为千位分隔符。

function formatMoney(amount, decimalCount = 2, decimal = '.', thousands = ',') {
    try {
        // Ensure the amount is a number and fix the decimal places
        decimalCount = Math.abs(decimalCount);
        decimalCount = isNaN(decimalCount) ? 2 : decimalCount;

        const negativeSign = amount < 0 ? '-' : '';
        let i = parseInt((amount = Math.abs(Number(amount) || 0).toFixed(decimalCount))).toString();
        let j = i.length > 3 ? i.length % 3 : 0;

        return (
            negativeSign +
            (j ? i.substr(0, j) + thousands : '') +
            i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousands) +
            (decimalCount
                ? decimal +
                    Math.abs(amount - i)
                        .toFixed(decimalCount)
                        .slice(2)
                : '')
        );
    } catch (e) {
        console.log(e);
    }
}

// Test cases
console.log(formatMoney(1234567.89)); // 1,234,567.89
console.log(formatMoney(1234567.89, 3)); // 1,234,567.890
console.log(formatMoney(-1234567.89, 2, '.', ',')); // -1,234,567.89
console.log(formatMoney(1234567.89, 0, '.', ',')); // 1,234,568
console.log(formatMoney(1234.56, 2, ',', '.')); // 1.234,56
Enter fullscreen mode Exit fullscreen mode

12. 截断段落

将段落截断为指定长度,如果截断,则添加省略号。

function truncateParagraph(paragraph, maxLength) {
    if (paragraph.length <= maxLength) {
        return paragraph;
    }
    return paragraph.slice(0, maxLength) + '...';
}

// Example usage
const paragraph =
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vitae eros eget tellus tristique bibendum. Donec rutrum sed sem quis venenatis.';

console.log(truncateParagraph(paragraph, 50));
// 'Lorem ipsum dolor sit amet, consectetur adipiscing...'
console.log(truncateParagraph(paragraph, 100));
// 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vitae eros eget tellus tristique b...'
Enter fullscreen mode Exit fullscreen mode

如果出于样式目的需要截断字符串,可以使用Tailwind CSS 的 `truncate` 或 `line-clamp`属性来实现。

JavaScript 中的常用对象工具

13. 检查值是否为对象

检查值是否为对象。

function isObject(value) {
    return value !== null && typeof value === 'object' && !Array.isArray(value);
}

console.log(isObject({ a: 1 })); // true
console.log(isObject([1, 2, 3])); // false
Enter fullscreen mode Exit fullscreen mode

14. 合并对象(平面对象)

将两个或多个对象合并为一个对象。

function mergeObjects(...objs) {
    return Object.assign({}, ...objs);
}

console.log(mergeObjects({ a: 1 }, { b: 2 }, { a: 3 })); // { a: 3, b: 2 }
Enter fullscreen mode Exit fullscreen mode

15. 深度合并对象

将两个或多个对象深度合并。

function deepMerge(...objects) {
    const isObject = (obj) => obj && typeof obj === 'object';

    return objects.reduce((prev, obj) => {
        Object.keys(obj).forEach((key) => {
            const prevVal = prev[key];
            const objVal = obj[key];

            if (Array.isArray(prevVal) && Array.isArray(objVal)) {
                prev[key] = prevVal.concat(...objVal);
            } else if (isObject(prevVal) && isObject(objVal)) {
                prev[key] = deepMerge(prevVal, objVal);
            } else {
                prev[key] = objVal;
            }
        });
        return prev;
    }, {});
}

const obj1 = { a: 1, b: { x: 10 } };
const obj2 = { b: { y: 20 }, c: 3 };
console.log(deepMerge(obj1, obj2)); // { a: 1, b: { x: 10, y: 20 }, c: 3 }
Enter fullscreen mode Exit fullscreen mode

16. 深度克隆对象

创建对象的深度克隆。

function deepClone(obj) {
    return JSON.parse(JSON.stringify(obj));
}

const original = { a: 1, b: { c: 2 } };
const clone = deepClone(original);
clone.b.c = 3;
console.log(original.b.c); // 2
console.log(clone.b.c); // 3
Enter fullscreen mode Exit fullscreen mode

请查看“在 Javascript 中克隆嵌套对象/数组的正确方法”以了解更多高级用例。

17. 从对象中省略/删除键

返回一个省略指定键的新对象。

function omitKeys(obj, keys) {
    const result = { ...obj };
    keys.forEach((key) => delete result[key]);
    return result;
}

console.log(omitKeys({ a: 1, b: 2, c: 3 }, ['a', 'c'])); // { b: 2 }
Enter fullscreen mode Exit fullscreen mode

18. 选择键以创建新对象

返回一个仅包含指定键的新对象。

function pickKeys(obj, keys) {
    const result = {};
    keys.forEach((key) => {
        if (obj.hasOwnProperty(key)) {
            result[key] = obj[key];
        }
    });
    return result;
}

console.log(pickKeys({ a: 1, b: 2, c: 3 }, ['a', 'c'])); // { a: 1, c: 3 }
Enter fullscreen mode Exit fullscreen mode

19. 反转对象键和值

反转对象的键和值。

function invertObject(obj) {
    const result = {};
    Object.keys(obj).forEach((key) => {
        result[obj[key]] = key;
    });
    return result;
}

console.log(invertObject({ a: 1, b: 2, c: 3 })); // { '1': 'a', '2': 'b', '3': 'c' }
Enter fullscreen mode Exit fullscreen mode

20. 检查对象是否为空

检查对象是否为空(没有可枚举属性)。

function isEmptyObject(obj) {
    return Object.keys(obj).length === 0;
}

console.log(isEmptyObject({})); // true
console.log(isEmptyObject({ a: 1 })); // false
Enter fullscreen mode Exit fullscreen mode

21. 地图对象

创建一个新对象,该对象具有相同的键,但其值经过函数转换。类似于array.map(),但适用于对象。

function mapObject(obj, fn) {
    const result = {};
    Object.keys(obj).forEach((key) => {
        result[key] = fn(obj[key], key);
    });
    return result;
}

console.log(mapObject({ a: 1, b: 2, c: 3 }, (value) => value * 2)); // { a: 2, b: 4, c: 6 }
Enter fullscreen mode Exit fullscreen mode

22. 过滤器对象

创建一个新对象,仅包含通过筛选函数的属性。类似于array.filter(),但针对的是对象。

function filterObject(obj, fn) {
    const result = {};
    Object.keys(obj).forEach((key) => {
        if (fn(obj[key], key)) {
            result[key] = obj[key];
        }
    });
    return result;
}

console.log(filterObject({ a: 1, b: 2, c: 3 }, (value) => value > 1)); // { b: 2, c: 3 }
Enter fullscreen mode Exit fullscreen mode

23. 冻结物体

冻结对象,使其不可更改。

function freezeObject(obj) {
    return Object.freeze(obj);
}

const obj = { a: 1, b: 2 };
const frozenObj = freezeObject(obj);
frozenObj.a = 3; // Will not change the value
console.log(frozenObj.a); // 1
Enter fullscreen mode Exit fullscreen mode

24. 深冻物体

深度冻结对象,使其及其所有嵌套对象都变为不可变。

function deepFreeze(obj) {
    Object.keys(obj).forEach((name) => {
        const prop = obj[name];
        if (typeof prop == 'object' && prop !== null) {
            deepFreeze(prop);
        }
    });
    return Object.freeze(obj);
}

const obj = { a: 1, b: { c: 2 } };
deepFreeze(obj);
obj.b.c = 3; // Will not change the value
console.log(obj.b.c); // 2
Enter fullscreen mode Exit fullscreen mode

JavaScript 中的常用数组工具

25. 基于指定函数的数组分组

根据指定的函数对数组元素进行分组。

function groupBy(array, fn) {
    const map = new Map();
    array.forEach((item) => {
        const key = fn(item);
        const collection = map.get(key);
        if (!collection) {
            map.set(key, [item]);
        } else {
            collection.push(item);
        }
    });
    return map;
}

const people = [
    { name: 'Alice', age: 21 },
    { name: 'Bob', age: 22 },
    { name: 'Charlie', age: 21 }
];

const groupedByAge = groupBy(people, (person) => person.age);
console.log(groupedByAge);
// Map { 21 => [{ name: 'Alice', age: 21 }, { name: 'Charlie', age: 21 }], 22 => [{ name: 'Bob', age: 22 }] }
Enter fullscreen mode Exit fullscreen mode

26. 数组交集

返回两个数组的交集。

function intersect(array1, array2) {
    return array1.filter((x) => array2.includes(x));
}

const array1 = [1, 2, 3, 4];
const array2 = [3, 4, 5, 6];
console.log(intersect(array1, array2)); // [3, 4]
Enter fullscreen mode Exit fullscreen mode

27. Zip 数组

将两个数组合并成一个包含键值对的数组。

function zip(array1, array2) {
    return array1.map((value, index) => [value, array2[index]]);
}

const array1 = [1, 2, 3];
const array2 = ['a', 'b', 'c'];
console.log(zip(array1, array2)); // [[1, 'a'], [2, 'b'], [3, 'c']]
Enter fullscreen mode Exit fullscreen mode

28. 删除重复项

从数组中删除重复值。

function uniqueArray(arr) {
    return [...new Set(arr)];
}

console.log(uniqueArray([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

29. 分割数组

将数组分割成指定大小的块。

function chunkArray(arr, size) {
    const result = [];
    for (let i = 0; i < arr.length; i += size) {
        result.push(arr.slice(i, i + size));
    }
    return result;
}

console.log(chunkArray([1, 2, 3, 4, 5], 2)); // [[1, 2], [3, 4], [5]]
Enter fullscreen mode Exit fullscreen mode

30. 数组差异

返回两个数组之间的差值。

function arrayDifference(arr1, arr2) {
    return arr1.filter((item) => !arr2.includes(item));
}

console.log(arrayDifference([1, 2, 3], [2, 3, 4])); // [1]
Enter fullscreen mode Exit fullscreen mode

JavaScript 中的常用日期工具

这些实用函数可以帮助您在 JavaScript 中高效地执行各种日期操作和格式化任务。

31. 不使用库格式化日期

将日期格式化为指定的字符串格式。

function formatDate(date, format) {
    const map = {
        mm: ('0' + (date.getMonth() + 1)).slice(-2),
        dd: ('0' + date.getDate()).slice(-2),
        yyyy: date.getFullYear(),
        hh: ('0' + date.getHours()).slice(-2),
        MM: ('0' + date.getMinutes()).slice(-2),
        ss: ('0' + date.getSeconds()).slice(-2)
    };

    return format.replace(/mm|dd|yyyy|hh|MM|ss/gi, (matched) => map[matched]);
}

const date = new Date();
console.log(formatDate(date, 'dd-mm-yyyy hh:MM:ss')); // Example: 28-07-2024 14:30:45
Enter fullscreen mode Exit fullscreen mode

32. 增加天数

在日期上加上指定的天数。

function addDays(date, days) {
    const result = new Date(date);
    result.setDate(result.getDate() + days);
    return result;
}

const date = new Date();
console.log(addDays(date, 5)); // Adds 5 days to the current date
Enter fullscreen mode Exit fullscreen mode

33. 减去天数

从日期中减去指定的天数。

function subtractDays(date, days) {
    const result = new Date(date);
    result.setDate(result.getDate() - days);
    return result;
}

const date = new Date();
console.log(subtractDays(date, 5)); // Subtracts 5 days from the current date
Enter fullscreen mode Exit fullscreen mode

34. 计算两个日期之间的天数

计算两个日期之间的天数。

function daysBetween(date1, date2) {
    const oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
    const diffDays = Math.round(Math.abs((date2 - date1) / oneDay));
    return diffDays;
}

const date1 = new Date('2024-07-01');
const date2 = new Date('2024-07-28');
console.log(daysBetween(date1, date2)); // Example: 27 days
Enter fullscreen mode Exit fullscreen mode

35. 检查日期是否为周末

检查给定日期是否为周末。

function isWeekend(date) {
    const day = date.getDay();
    return day === 0 || day === 6;
}

const date = new Date();
console.log(isWeekend(date)); // Returns true if the date is a weekend, otherwise false
Enter fullscreen mode Exit fullscreen mode

36. 计算一个月的天数

获取特定年份特定月份的天数。

function getDaysInMonth(month, year) {
    return new Date(year, month + 1, 0).getDate();
}

const month = 6; // July
const year = 2024;
console.log(getDaysInMonth(month, year)); // Example: 31 days in July 2024
Enter fullscreen mode Exit fullscreen mode

37. 两个日期之间的持续时间

function getDuration(startDate, endDate) {
    const diff = endDate - startDate;
    return Math.floor(diff / (1000 * 60 * 60));
    // 1000 * 60 * 60 for duration in hours
    // 1000 * 60 * 60 * 24 for duration in days
    // 1000 * 60 for duration in minutes
}
const startDate = new Date('2024-07-01T12:00:00');
const endDate = new Date('2024-07-01T15:30:00');
console.log(getDurationInHours(startDate, endDate)); // Duration in hours
Enter fullscreen mode Exit fullscreen mode

对于更高级的日期使用场景和经过测试的实用工具,可以考虑使用像 day.js 这样的日期库。

结论

我们介绍了 37 个实用的 JavaScript 工具函数,它们可以帮助你更高效地编写代码。这些函数简化了数组处理、日期格式化和字符串操作等任务。使用它们可以节省你的时间并减少代码错误。

如果这篇文章对您有帮助,请分享给其他可能从中受益的人。您可以将其收藏以便日后查阅。如果您有任何文中未提及的实用函数,欢迎在评论区分享。

祝您编程愉快!

文章来源:https://dev.to/syakirurahman/37-common-javascript-utility-functions-for-string-object-array-date-2afb