likes
comments
collection
share

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

作者站长头像
站长
· 阅读数 15

10个让你爱不释手的一行Javascript代码 在这篇博客中,我们将分享 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); // [1, 2, 3, 4, 5, 6]

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

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) // 2, 1

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

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

计算两个日期之间的间隔

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('');     // string
getType(0);      // number
getType();       // undefined
getType(null);   // null
getType({});     // object
getType([]);     // array
getType(0);      // number
getType(() => {});  // function

检测对象是否为空

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

系列文章

我的更多前端资讯

欢迎大家技术交流 资料分享 摸鱼 求助皆可 —链接