JS中非常实用的『一行代码』

导读: 最近在国外技术社区看到了一些关于 一行代码 的文章📄,感觉很有意思,就整理了下来并且自己额外补充了一部分分享给大家🤜,希望对各位读者们有所帮助💕。

最近一次更新时间 2022-08-21 12:00:15

这些方法使用到了一些API,简化了操作,但是有些方法写一行属实不太优雅,所以这里主要还是学习API的使用小技巧。

一、日期处理

  1. 检查日期是否有效
    该方法用于检测给出的日期是否有效
1
2
3
const isDateValid = (...val) => !Number.isNaN( new Date(...val).valueOf() );
// how to use
isDateValid("December 17, 1995 03:24:00"); // => true
  1. 计算两个日期之间的间隔
    该方法用于计算两个日期之间的间隔时间(day)
1
2
3
const dayDif = (date1, date2) => Math.ceil( Math.abs( date1.getTime() - date2.getTime() ) / 86400000);
// how to use
dayDif(new Date("2022-08-01"), new Date("2022-08-04")); // => 3
  1. 查找日期位于一年中的第几天
    该方法用于检测给出的日期位于今年的第几天
1
2
3
4
const dayOfYear = date => Math.floor( ( date - new Date(date.getFullYear(), 0, 0) ) / 1000 / 60 / 60 / 24 )
// how to use
dayOfYear(new Date("2022-08-01")); // => 213
dayOfYear(new Date("2022-01-01")); // => 1
  1. 时间格式化
    该方法用于转换时间
1
2
3
4
5
const timeFromDate = date => date.toTimeString().slice(0, 8);
// how to use
timeFromDate(new Date(2022, 08, 04, 12, 30, 0)); // => '12:30:00'
timeFromDate(new Date(2022, 08, 04, 12, 30, 60)); // => '12:31:00'
timeFromDate(new Date()); // => 此刻的时间

二、字符串处理

  1. 字符串首字母大写
    该方法用于将英文字符串的首字母大写处理
1
2
3
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
// how to use
capitalize("hello world"); // => Hello world
  1. 翻转字符串
    该方法用于将一个字符串进行翻转操作并返回翻转后的内容
1
2
3
const reverse = str => str.split('').reverse().join('');
// how to use
reverse("hello world"); // => dlrow olleh
  1. 随机字符串
    该方法用于生成一个随机的字符串并返回
1
2
3
const randomString = () => Math.random().toString(36).slice(2);
// how to use
randomString(); // => anyString
  1. 去除字符串中的HTML
    该方法用于去除字符串中的HTML元素
1
2
3
const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
// how to use
stripHtml("<div>Beware of the missing closing tag</div>hello world<i>!<i>"); // => 'Beware of the missing closing taghello world!'
  1. 获取URL的search参数并json化
    该方法用于获取当前访问的URL中的search内容并解析成JSON键值对形式
1
2
3
const urlParams = search => Object.fromEntries(new URLSearchParams(search));
// how to use
urlParams(location.search); // => { id: '1', name: 'rexhang' }
  1. 去除数字之外的所有字符
    该方法用于去除数字之外的所有字符
1
2
3
4
const toNumber = str => Number(str.replace(/\D/g, ''));
// how to use
const str = 'hello 123 is god 456';
toNumber(str); // => 123456
  1. 空值(null | undefined)合并运算符
    该方法用于更简短的定义空值情况下的时候, null 或者 undefined 会认定为判断范围, 其余认为正常赋值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const aa = isA ?? false;
const bb = isB ?? 'hello';
const cc = isC ?? 'ok';
const dd = isD ?? 'done';
// how to use
const isA = null;
const isB = '';
const isC = undefined;
const isD = false;
const aa = isA ?? '...';
const bb = isB ?? 'hello';
const cc = isC ?? 'ok';
const dd = isD ?? 'done';
console.log(aa, bb, cc, dd);

二、数组处理

  1. 从数组中移除重复项
    该方法用于从数组中移除重复项
1
2
3
const removeDuplicates = arr => [...new Set(arr)];
// how to use
removeDuplicates([1, 1, 3, 4, 1, 5]); // => [1, 3, 4, 5]
  1. 打乱数组顺序
    该方法用于打乱数组顺序,随机取random后的数组
1
2
3
4
const randomArr = arr => arr.sort(() => 0.5 - Math.random());
// how to use
const arr = ['🙂', '66', true, 11, {name: 'rexhang'}];
console.log(randomArr(arr)); // random arr, eg: ['66', 11, true, {name: 'rexhang'}, '🙂'];
  1. 从数组中随机去一个值
    该方法用于从数组中随机去一个值
1
2
3
4
const takeARandomItem = arr => arr[Math.floor(Math.random() * arr.length)]
// how to use
const eles = ['🙂', '66', true, 11, {name: 'rexhang'}];
console.log(takeARandomItem(eles)); // random item of arr, eg: '🙂';
  1. 从数组中取出最大/小值(仅限数字|字符串数字)
    该方法用于从数组中取出最大/小值(仅限数字|字符串数字)
1
2
3
4
5
6
7
const getMaxMinValue = arr => ({
max: Math.max(...arr),
min: Math.min(...arr),
})
// how to use
const items = [11, 12, 11, 1, '0'];
console.log(getMaxMinValue(items)); // { max: 12, min: 0 }
  1. 判断数组是否为空
    该方法用于判断数组是否为空
1
2
3
4
5
const isNotEmpty = arr => Array.isArray(arr) && !!arr.length;
// how to use
isNotEmpty([1, 3]); // => true
isNotEmpty([]); // => true
isNotEmpty("[1, 3]"); // => 非数组返回false

长期且持续更新中…