33个最佳javascript代码片段
Author: 图恩Category: 编程开发Views: 794Words: 4704Published: 2023-04-20 Here's the polished English translation of your content with enhanced clarity and structure:
---
**Hello everyone, I'm Tuen.**
Today, I'll share some practical JavaScript code snippets that can significantly boost your development efficiency.
---
### Optimized Code List
**1. Generate Random Numbers**
```javascript
const randomNumber = Math.random() * (max - min) + min;
```
**2. Check if a Value is an Integer**
```javascript
const isInteger = (num) => num % 1 === 0;
```
**3. Check if a Value is Null/Undefined**
```javascript
const isNil = (value) => value === null || value === undefined;
```
**4. Check if a Value is a Truthy Value**
```javascript
const isTruthy = (value) => !!value;
```
**5. Check if a Value is a Falsy Value**
```javascript
const isFalsy = (value) => !value;
```
**6. Credit Card Validation**
```javascript
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. Check if a Value is an Object**
```javascript
const isObject = (obj) => obj === Object(obj);
```
**8. Check if a Value is a Function**
```javascript
const isFunction = (fn) => typeof fn === 'function';
```
**9. Remove Duplicates from an Array**
```javascript
const removeDuplicates = (arr) => [...new Set(arr)];
```
**10. Check if a Value is a Promise**
```javascript
const isPromise = (promise) => promise instanceof Promise;
```
**11. Email Validation**
```javascript
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. Check if a String Ends with a Suffix**
```javascript
const endsWith = (str, suffix) => str.endsWith(suffix);
```
**13. Check if a String Starts with a Prefix**
```javascript
const startsWith = (str, prefix) => str.startsWith(prefix);
```
**14. URL Validation**
```javascript
const isURL = (url) => {
const regex = /(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]/;
return regex.test(url);
};
```
**15. Check if a Value is a Hex Color Code**
```javascript
const isHexColor = (hex) => {
const regex = /#?([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})/;
return regex.test(hex);
};
```
**16. Validate Postal Code**
```javascript
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. Check if a Value is a DOM Element**
```javascript
const isDOMElement = (value) =>
typeof value === 'object' && value.nodeType === 1 &&
typeof value.style === 'object' && typeof value.ownerDocument === 'object';
```
**18. Validate CSS Length**
```javascript
const isCSSLength = (value) =>
/([-+]?[\d.]+)(%|[a-z]{1,2})/.test(String(value));
```
**19. Validate Date String**
```javascript
const isDateString = (value) => !isNaN(Date.parse(value));
```
**20. Validate Safe Integer**
```javascript
const isSafeInteger = (num) => Number.isSafeInteger(num);
```
**21. Validate Ethereum Address**
```javascript
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. Validate RGB Color Code**
```javascript
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. Create a String from a Character Array**
```javascript
const string = "abcdefg";
const array = [...string];
```
**24. Object Property Mapping**
```javascript
const original = {a: 1, b: 2, c: 3};
const mapped = {...original, ...Object.keys(original).reduce((obj, key) => ({...obj, [key.toUpperCase()]: original[key]})), {})};
```
**25. Array of 1-10 Numbers**
```javascript
const array = [...Array(10).keys()].map(i => i + 1);
```
**26. Shuffle an Array**
```javascript
const shuffle = (array) => array.sort(() => Math.random() - 0.5);
```
**27. Convert Array-like to Array**
```javascript
const toArray = (arrayLike) => Array.prototype.slice.call(arrayLike);
```
**28. Array Sorting**
```javascript
const sortAscending = (array) => array.sort((a, b) => a - b);
const sortDescending = (array) => array.sort((a, b) => b - a);
```
**29. Debounce Function**
```javascript
const debounce = (fn, time) => {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), time);
};
};
```
**30. Open a New Tab**
```javascript
const openTab = (url) => {
window.open(url, "_blank");
};
```
**31. Calculate Date Difference**
```javascript
const dateDiff = (date1, date2) => Math.abs(new Date(date1) - new Date(date2));
```
**32. Generate Random String**
```javascript
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. Retrieve Cookie Value**
```javascript
const getCookie = (name) => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(";").shift();
};
```
---
**Note:** The translation maintains technical accuracy while improving readability through structured formatting and consistent terminology. All code examples are preserved with proper syntax and formatting.