一些短小但令人惊叹的 JavaScript 代码:
- 翻转字符串:
const reverseString = str => str.split("").reverse().join("");
- 判断回文字符串:
const isPalindrome = str => str === str.split("").reverse().join("");
code>
查找数组中的最大值:
const arr = [1, 2, 3, 4, 5];
const maxNum = Math.max(...arr);
数组去重:
const arr = [1, 1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [...new Set(arr)];
计算数组中的总和:
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((total, num) => total + num);
交换两个变量的值:
let a = 1, b = 2;
[b, a] = [a, b];
筛选出符合条件的数组元素:
const arr = [1, 2, 3, 4, 5];
const filteredArr = arr.filter(num => num % 2 === 0);
数组扁平化:
const arr = [1, [2, [3, [4]]]];
const flattenedArr = arr.flat(Infinity);
数组乱序:
const arr = [1, 2, 3, 4, 5];
const shuffledArr = arr.sort(() => Math.random() - 0.5);
防抖:
const debounce = (func, delay) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => func(...args), delay);
};
};
节流:
const throttle = (func, limit) => {
let inThrottle;
return (...args) => {
if (!inThrottle) {
inThrottle = true;
func(...args);
setTimeout(() => inThrottle = false, limit);
}
};
};
判断变量是否为数组:
const arr = [1, 2, 3];
const isArray = Array.isArray(arr);
对象属性解构:
const obj = { x: 1, y: 2 };
const { x, y } = obj;
深拷贝对象:
const deepCopy = obj => JSON.parse(JSON.stringify(obj));
求数组中的平均值:
const arr = [1, 2, 3, 4, 5];
const average = arr.reduce((total, num) => total + num) / arr.length;
检查字符串是否以指定的字符串开头:
const str = "Hello, world!";
const startsWithHello = str.startsWith("Hello");
检查字符串是否以指定的字符串结尾:
const str = "Hello, world!";
const endsWithWorld = str.endsWith("world!");
快速判断一个数字是否是偶数:
const isEven = num => (num & 1) === 0;
将数字格式化为货币:
const amount = 12345.67;
const formattedAmount = amount.toLocaleString("en-US", { style: "currency", currency: "USD" });
创建指定长度和默认值的数组:
const length = 5;
const defaultValue = 0;
const arr = Array.from({ length }, () => defaultValue);
使用 Promise.all 并行处理多个异步操作:
const urls = ["https://example.com/api/1", "https://example.com/api/2", "https://example.com/api/3"];
const requests = urls.map(url => fetch(url));
const responses = await Promise.all(requests);
const data = await Promise.all(responses.map(response => response.json()));
这些代码同样具有高效和易用性,但在实际项目中需要注意其上下文和使用场景,以确保其正确性和有效性。