33个最佳javascript代码片段
大家好我是图恩,今天我想分享一些我保存的有用的 JavaScript 代码片段,我认为这些代码片段可以帮助您更轻松地完成开发人员的生活。
让我们开始吧!
1.在两个值之间生成一个随机数:const randomNumber = Math.random() * (max - min) + min
2.检查数字是否为整数:const isInteger = (num) => num % 1 === 0
3.检查值是否为 或 :nullundefinedconst 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());
} else {
// Add regex for other country codes as needed
return false;
}
}
17.检查值是否为 DOM 元素
const isDOMElement = (value) => typeof value === 'object' && value.nodeType === 1 && typeof value.style === 'object' && typeof value.ownerDocument === 'object';
18.检查值是否为有效的 CSS 长度(例如、、):10px 1em 50%
const isCSSLength = (value) => /([-+]?[\d.]+)(%|[a-z]{1,2})/.test(String(value));
19.检查值是否为有效的日期字符串(例如、、):2022-09-01 September 1, 20229/1/2022
const isDateString = (value) => !isNaN(Date.parse(value));
20.检查值是否是表示安全整数的数字(那些可以在 JavaScript 中准确表示的整数):const isSafeInteger = (num) => Number.isSafeInteger(num)
21.检查值是否为有效的加密地址
//Ethereum
const isEthereumAddress = (address) => {
const regex = /0x[a-fA-F0-9]{40}/;
return regex.test(address);
}
//bitcoin
const isBitcoinAddress = (address) => {
const regex = /[13][a-km-zA-HJ-NP-Z0-9]{25,34}/;
return regex.test(address);
}
// ripple
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.将类似数组的对象(如 NodeList)转换为数组:
onst toArray = (arrayLike) => Array.prototype.slice.call(arrayLike);
28.数组排序
//Ascending
const sortAscending = (array) => array.sort((a, b) => a - b);
//Descending
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.使用给定 URL 打开一个新选项卡:
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();
};
发表评论 (审核通过后显示评论):