JS - common methods 🎢
-
反转字符串:使用一行代码反转字符串:
const reversedString = str.split('').reverse().join('');
-
数组求和:使用
reduce()
方法计算数组中所有元素的和:const sum = numbers.reduce((acc, curr) => acc + curr, 0);
-
查找数组中的最大值和最小值:使用扩展运算符和
Math.max()
、Math.min()
:const max = Math.max(...numbers); const min = Math.min(...numbers);
-
去除数组中的重复项:使用
Set
创建一个不含重复项的新数组:const uniqueArray = [...new Set([1, 2, 2, 3])];
-
扁平化多维数组:使用
flat()
方法将嵌套数组扁平化:const flatArray = nestedArray.flat(2);
-
复制文本到剪贴板:使用剪贴板 API 复制文本:
function copyText(text) { navigator.clipboard.writeText(text); }
-
检查值是否为数字:使用
typeof
和!isNaN()
检查:const isNumber = value => typeof value === 'number' && !isNaN(value);
-
生成范围内的随机数:生成两个值之间的随机数:
const getRandom = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
-
将字符串转换为数字:使用
+
操作符快速转换:const num = +"42"; // 42
-
函数中的默认参数:设置默认参数值以避免未定义的值:
function greet(name = 'Guest') { console.log(`Hello, ${name}`); }
-
将参数对象转换为数组:将函数中的
arguments
转换为实际数组:const argsArray = Array.from(arguments);
-
防抖函数:确保函数不会在短时间内被多次调用:
function debounce(func, delay) { let timeout; return function(...args) { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), delay); }; }
-
节流函数:确保函数在指定时间内最多只被调用一次:
function throttle(func, limit) { let lastFunc; let lastRan; return function(...args) { if (!lastRan) { func.apply(this, args); lastRan = Date.now(); } else { clearTimeout(lastFunc); lastFunc = setTimeout(() => { if (Date.now() - lastRan >= limit) { func.apply(this, args); lastRan = Date.now(); } }, limit - (Date.now() - lastRan)); } }; }
-
检查对象是否为空:使用
Object.keys()
检查对象是否没有属性:const isEmpty = obj => Object.keys(obj).length === 0;
-
短路求值:使用短路运算符条件赋值:
const message = user.isLoggedIn && "Welcome back!";
-
对象属性简写:当属性名与变量名相同时,可以使用简写语法:
const person = { name, age };
-
数组解构赋值:将数组中的值赋给变量:
const [first, second] = [10, 20];
-
对象解构赋值:从对象中提取属性并赋给变量:
const {name, age} = {name: "Jane", age: 30};
-
模板字面量:用于方便的字符串插值:
const greeting = `Hello, ${name}!`;
-
将 NodeList 转换为数组:使用
Array.from()
转换 NodeList:const nodeArray = Array.from(nodeList);
-
检查数组是否包含某个元素:使用
includes()
方法检查值是否存在于数组中:console.log(fruits.includes('banana')); // true
-
获取数组中的唯一值:可以使用
Set
获取唯一值:const uniqueValues = Array.from(new Set([1, 2, 2, 3, 3]));
-
查找对象属性:使用
Object.keys()
和Object.values()
获取对象的键和值:console.log(Object.keys(obj)); // ['name', 'age'] console.log(Object.values(obj)); // ['Alice', 30]
-
合并对象:使用扩展运算符合并对象:
const mergedObj = { ...obj1, ...obj2 };
-
映射数组:使用
map()
方法对每个元素应用函数进行转换:const doubled = numbers.map(num => num * 2); // [2, 4, 6]
-
过滤数组:过滤掉不需要的元素:
const evens = numbers.filter(num => num % 2 === 0); // [2, 4]
-
Promise.all():同时处理多个异步任务:
Promise.all([fetch('/data1'), fetch('/data2')]) .then(responses => { /* Handle responses */ }) .catch(error => console.error(error));
-
将 Set 转换为数组:使用扩展运算符将 Set 转换为数组:
const array = [...set];
-
对数组进行排序:对数字数组进行升序或降序排序:
numbers.sort((a, b) => a - b); // 升序 numbers.sort((a, b) => b - a); // 降序
-
填充字符串:在字符串的开始或结束填充以达到指定长度:
const paddedStr = str.padStart(3, '0'); // "005"
-
去除空格:使用
trim()
、trimStart()
和trimEnd()
去除空格:console.log(text.trim()); // "Hello"
-
检查字符串是否包含子串:使用
includes()
检查字符串中是否包含特定子串:console.log(sentence.includes("awesome")); // true
-
查找子串索引:使用
indexOf()
查找子串的位置:console.log(sentence.indexOf("fun")); // 14
-
重复字符串:使用
repeat()
重复字符串:console.log(str.repeat(3)); // "hahaha"
-
替换子串:使用
replace()
替换子串:const newText = text.replace("fun", "awesome");
-
可选链操作符:安全访问嵌套属性,避免错误:
console.log(user?.address?.city); // undefined,无错误发生
-
将日期转换为本地字符串格式:格式化日期为本地日期字符串:
console.log(date.toLocaleDateString('en-US')); // MM/DD/YYYY 格式
-
检查值是否为数组:使用
Array.isArray()
检查是否为数组:console.log(Array.isArray([1, 2, 3])); // true
-
检查 DOM 中元素是否存在:使用
document.querySelector()
检查元素存在性:const elementExists = !!document.querySelector('.my-element');
-
获取当前时间戳:使用
Date.now()
获取当前时间戳:const timestamp = Date.now();
-
格式化带逗号的数字:使用
toLocaleString()
格式化数字带逗号分隔符:console.log(number.toLocaleString()); // "1,234,567"
-
将数字四舍五入到两位小数:使用
toFixed()
四舍五入数字到两位小数:console.log(number.toFixed(2)); // "5.68"
-
检查变量是否未定义:检查变量是否未定义:
if (typeof variable === 'undefined') { /* Handle undefined */ }
-
从数组中获取随机项: 使用 Math.random() 从数组中获取随机项:
const randomItem = items[Math.floor(Math.random() * items.length)];
-
简洁函数的箭头函数用法: 使用箭头函数提供简洁语法:
const add = (a, b) => a + b;
-
浅拷贝对象: 使用 Object.assign() 拷贝对象:
const copy = Object.assign({}, original);
-
类型检查: 使用 typeof 检查变量类型:
console.log(typeof 'Hello'); // "string"
-
动态属性名: 使用方括号设置动态属性名:
const obj = { [key]: 'John' };
-
检查空值: 使用空合并运算符处理空或未定义的值:
const value = user.age ?? 'Unknown';
-
更易调试的表格显示: 使用 console.table() 在控制台显示表格数据:
console.table(users);