10个让你爱不释手的一行Javascript代码

本文分享了10+个JavaScript一行代码示例,涵盖数组操作、字符串处理、异步编程、对象排序和类型检测等,帮助开发者提升编码效率和代码简洁度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这篇博客中,我们将分享 10+ 个实用的一行 JavaScript 代码,这些代码可以帮助你提高编码效率和代码简洁度。这些代码片段将涵盖各种用途,从操作数组和字符串,到更高级的概念,如异步编程和面向对象编程。

获取数组中的随机元素

使用 Math.random() 函数和数组长度可以轻松获取数组中的随机元素:

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

数组扁平化

使用 reduce() 函数和 concat() 函数可以轻松实现数组扁平化:

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

对象数组根据某个属性值进行排序

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

从数组中删除特定元素

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

检查数组中是否存在重复项

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

判断数组是否包含某个值

const hasValue = arr.includes(value);

首字母大写

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

获取随机整数

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

获取随机字符串

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

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

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

将字符串转换为小驼峰式命名:

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

计算两个日期之间的间隔

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

查找日期位于一年中的第几天

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

复制内容到剪切板

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

copyToClipboard("Hello World");

获取变量的类型

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

getType('');     
getType(0);      
getType();       
getType(null);   
getType({});     
getType([]);     
getType(0);      
getType(() => {});  

检测对象是否为空

const isEmptyObject = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Web面试那些事儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值