16个 JavaScript 单行代码帮助你提升开发水平

01、获取数组中的随机元素

使用 Math.random() 函数结合数组的长度,从数组中获取随机元素非常轻松:

const arr = [1, 2, 3, 4, 5];
const randomElement = arr[Math.floor(Math.random() * arr.length)];
console.log(randomElement);

02、轻松展平数组

使用 reduce() 和 concat() 函数将嵌套数组展平为单层:

const arr = [[1, 2], [3, 4], [5, 6]];
const flattenedArr = arr.reduce((acc, cur) => acc.concat(cur), []);
console.log(flattenedArr); // Output: [1, 2, 3, 4, 5, 6]

03、按属性对数组进行排序

只需根据特定属性的值对对象数组进行排序:

const sortedArray = array.sort((a, b) => (a.property > b.property ? 1 : -1));

04、删除特定元素

你可以轻松地从数组中过滤掉不需要的元素:

const removedArray = array.filter((item) => item !== elementToRemove);

05、检查数组中的重复项

检测数组是否包含任何重复项:

const hasDuplicates = (array) => new Set(array).size !== array.length;

06、数组值存在性检查

快速确定数组是否包含特定值:

const hasValue = arr.includes(value);

07、将首字母大写

将字符串的首字母转换为大写:

const capitalized = str.charAt(0).toUpperCase() + str.slice(1);

08、生成随机整数

在内创建一个随机整数特定范围:

const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;

09、获取随机字符串

生成指定长度的随机字符串:

const randomStr = Math.random().toString(36).substring(2, length);

10、交换变量值

使用解构和 rest 运算符轻松交换两个变量的值:

let a = 1, b = 2;
[b, a] = [a, b];
console.log(a, b); // 2, 1

11、将字符串转换为驼峰式大小写

轻松将任何字符串转换为驼峰式大小写格式:

const str = 'hello world';
const camelCase = str.replace(/\s(.)/g, ($1) => $1.toUpperCase()).replace(/\s/g, '').replace(/^(.)/, ($1) => $1.toLowerCase());
console.log(camelCase); // "helloWorld"

12、计算时间间隔

查找两个日期之间的天数:

const diffInDays = (dateA, dateB) => Math.floor((dateB - dateA) / (1000 * 60 * 60 * 24));

13、发现一年中的哪一天

计算特定日期属于一年中的哪一天:

const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

14、复制到剪贴板

轻松将文本复制到剪贴板:

const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");

15、识别变量类型

确定 JavaScript 中任何变量的类型:

const getType = (variable) => Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
getType(''); // string

16、检查对象是否为空

快速验证对象是否没有属性:

const isEmptyObject = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值