33个最佳javascript代码片段
大家好,我是图恩。今天分享一些我整理的实用JavaScript代码片段,这些代码能显著提升开发效率。
以下为优化后的代码列表:
1. 生成随机数
const randomNumber = Math.random() * (max - min) + min
2. 判断是否为整数
const isInteger = (num) => num % 1 === 0
3. 判断是否为null/undefined
const isNil = (value) => value === null || value === undefined
4. 判断是否为真值
const isTruthy = (value) => !!value
5. 判断是否为假值
const isFalsy = (value) => !value
6. 信用卡验证
const isCreditCard = (cc) => {
const regex = /(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-7][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})/;
return regex.test(cc);
};7. 判断是否为对象
const isObject = (obj) => obj === Object(obj)
8. 判断是否为函数
const isFunction = (fn) => typeof fn === 'function'
9. 去重数组
const removeDuplicates = (arr) => [...new Set(arr)];
10. 判断是否为承诺
const isPromise = (promise) => promise instanceof Promise
11. 邮件验证
const isEmail = (email) => {
const regex = /(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
return regex.test(email);
};12. 字符串末尾检查
const endsWith = (str, suffix) => str.endsWith(suffix)
13. 字符串开头检查
const startsWith = (str, prefix) => str.startsWith(prefix)
14. URL验证
const isURL = (url) => {
const regex = /(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]/;
return regex.test(url);
};15. 颜色代码验证
const isHexColor = (hex) => {
const regex = /#?([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})/;
return regex.test(hex);
};16. 邮政编码验证
const isPostalCode = (postalCode, countryCode) => {
if (countryCode === 'US') {
const regex = /[0-9]{5}(?:-[0-9]{4})?/;
return regex.test(postalCode);
} else if (countryCode === 'CA') {
const regex = /[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] [0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]/;
return regex.test(postalCode.toUpperCase());
}
// 添加其他国家代码的正则表达式
return false;
};17. 判断是否为DOM元素
const isDOMElement = (value) => typeof value === 'object' && value.nodeType === 1 && typeof value.style === 'object' && typeof value.ownerDocument === 'object';18. CSS长度验证
const isCSSLength = (value) => /([-+]?[\d.]+)(%|[a-z]{1,2})/.test(String(value));19. 日期字符串验证
const isDateString = (value) => !isNaN(Date.parse(value));20. 安全整数验证
const isSafeInteger = (num) => Number.isSafeInteger(num);21. 加密地址验证
const isEthereumAddress = (address) => {
const regex = /0x[a-fA-F0-9]{40}/;
return regex.test(address);
};
const isBitcoinAddress = (address) => {
const regex = /[13][a-km-zA-HJ-NP-Z0-9]{25,34}/;
return regex.test(address);
};
const isRippleAddress = (address) => {
const regex = /r[0-9a-zA-Z]{33}/;
return regex.test(address);
};22. RGB颜色代码验证
const isRGBColor = (rgb) => {
const regex = /rgb\(\s*([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\s*,\s*([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\s*,\s*([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\s*\)/;
return regex.test(rgb);
};23. 字符数组创建
const string = "abcdefg";
const array = [...string];24. 对象属性映射
const original = {a: 1, b: 2, c: 3};
const mapped = {...original, ...Object.keys(original).reduce((obj, key) => ({...obj, [key.toUpperCase()]: original[key]})), {})};25. 1-10数字数组
const array = [...Array(10).keys()].map(i => i + 1);26. 数组打乱
const shuffle = (array) => array.sort(() => Math.random() - 0.5);27. 类似数组转数组
const toArray = (arrayLike) => Array.prototype.slice.call(arrayLike);28. 数组排序
const sortAscending = (array) => array.sort((a, b) => a - b);
const sortDescending = (array) => array.sort((a, b) => b - a);29. 防抖函数
const debounce = (fn, time) => {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), time);
};
};30. 打开新选项卡
const openTab = (url) => {
window.open(url, "_blank");
};31. 日期差值计算
const dateDiff = (date1, date2) => Math.abs(new Date(date1) - new Date(date2));32. 随机字符串生成
const randomString = (length) => {
let result = "";
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
};33. 获取cookie值
const getCookie = (name) => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(";").shift();
};
发表评论 (审核通过后显示评论):