在这篇博客中,我们将分享 10+ 个实用的一行 JavaScript 代码,这些代码可以帮助你提高编码效率和代码简洁度。这些代码片段将涵盖各种用途,从操作数组和字符串,到更高级的概念,如异步编程和面向对象编程。
获取数组中的随机元素
使用 Math.random() 函数和数组长度可以轻松获取数组中的随机元素:
1 2 3
| const arr = [1, 2, 3, 4, 5]; const randomElement = arr[Math.floor(Math.random() * arr.length)]; console.log(randomElement);
|
数组扁平化
使用 reduce() 函数和 concat() 函数可以轻松实现数组扁平化:
1 2 3
| const arr = [[1, 2], [3, 4], [5, 6]]; const flattenedArr = arr.reduce((acc, cur) => acc.concat(cur), []); console.log(flattenedArr);
|
对象数组根据某个属性值进行排序
1
| const sortedArray = array.sort((a, b) => (a.property > b.property ? 1 : -1));
|
从数组中删除特定元素
1
| const removedArray = array.filter((item) => item !== elementToRemove);
|
检查数组中是否存在重复项
1
| const hasDuplicates = (array) => new Set(array).size !== array.length;
|
首字母大写
1
| const capitalized = str.charAt(0).toUpperCase() + str.slice(1);
|
获取随机整数
1
| const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
|
获取随机字符串
1
| const randomStr = Math.random().toString(36).substring(2, length);
|
使用解构和 rest 运算符交换变量的值
1 2 3
| let a = 1, b = 2 [b, a] = [a, b] console.log(a, b)
|
将字符串转换为小驼峰式命名
1 2 3
| const str = 'hello world' const camelCase = str.replace(/\s(.)/g, ($1) => $1.toUpperCase()).replace(/\s/g, '').replace(/^(.)/, ($1) => $1.toLowerCase()) console.log(camelCase)
|
计算两个日期之间的间隔
1
| const diffInDays = (dateA, dateB) => Math.floor((dateB - dateA) / (1000 * 60 * 60 * 24));
|
查找日期位于一年中的第几天
1
| const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
|
复制内容到剪切板
1 2 3
| const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
|
获取变量的类型
1 2 3 4 5 6 7 8 9 10
| const getType = (variable) => Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
getType(''); getType(0); getType(); getType(null); getType({}); getType([]); getType(0); getType(() => {});
|
检测对象是否为空
1
| const isEmptyObject = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;
|