跳到主要内容

js方法

01、等待特定的时间量(以毫秒为单位)

const wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));

await wait(1000); // waiting 1 second

02、检查日期是否为工作日

const isWeekday = (d: Date): boolean => d.getDay() % 6 !== 0;

isWeekday(new Date(2022, 2, 21)); // -> true
isWeekday(new Date(2021, 2, 20)); // -> false

03、反转字符串

const reverse = (s: string): string => s.split('').reverse().join('');

reverse('elon musk'); // -> 'ksum nole'

04、检查一个数字是否为偶数

const isEven = (n: number): boolean => n % 2 === 0;

isEven(2); // -> true
isEven(3); // -> false

05、大写字符串

const capitalize = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1);

capitalize('lorem ipsum'); // -> Lorem ipsum

06、检查数组是否为空

const isArrayEmpty = (arr: unknown[]): boolean => Array.isArray(arr) && !arr.length;

isArrayEmpty([]); // -> true
isArrayEmpty([1, 2, 3]); // -> false

07、检查对象/数组是否为空

const isObjectEmpty = (obj: unknown): boolean => obj && Object.keys(obj).length === 0;

isObjectEmpty({}); // -> true
isObjectEmpty({ foo: 'bar' }); // -> false

08、随机生成整数

基于两个参数生成一个随机整数。

const randomInteger = (min: number, max: number): number => Math.floor(Math.random() * (max - min + 1)) + min;

randomInteger(1, 10); // -> 7

09、生成随机布尔值

const randomBoolean = (): boolean => Math.random() >= 0.5;

randomBoolean(); // -> true

10、切换布尔值

切换布尔值,变假为真,变真为假。

const toggleBoolean = (val: boolean): boolean => (val = !val);

toggleBoolean(true); // -> false

11、转换

将字符串转换为带“-”的连字字符串。

const slugify = (str: string): string => str.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '');

slugify('Hello World'); // -> hello-world

12、生成随数组组合

随机生成一组任何类型的数组。

const shuffleArray = <T>(arr: T[]): T[] => arr.sort(() => Math.random() - 0.5);

shuffleArray(<number[]>[1, 2, 3, 4, 5]); // -> [ 4, 5, 2, 1, 3 ]

13、将连字字符串转换为骆峰字符串

const snakeToCamel = (s: string): string => s.toLowerCase().replace(/(_\w)/g, (w) => w.toUpperCase().substring(1));

snakeToCamel('foo_bar'); // -> fooBar

14、随机整数

根据当前时间生成一个随机整数。

const randomInteger = (): number => new Date().getTime();

randomInteger(); // -> 1646617367345

15、随机数字符串

根据当前时间生成随机数字符串。

const randomNumberString = (): string => new Date().getTime() + Math.random().toString(36).slice(2);

randomNumberString(); // -> 1646617484381wml196a8iso

16、将数字转换为字符/字母

const numberToLetter = (value: number): string => String.fromCharCode(94 + value);

numberToLetter(4); // -> b

17、生成随机的十六进制颜色

const randomHexColor = (): string => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0')}`;

randomHexColor(); // -> #dc7c40

18、删除字符串的尾部斜杠

const removeTrailingSlash = (value: string): string => value && value.charAt(value.length - 1) === '/' ? value.slice(0, -1) : value;

removeTrailingSlash('foo-bar/'); // -> foo-bar

19、获取数组的随机项

const randomItem = <T>(arr: T[]): T => arr[(Math.random() * arr.length) | 0];

randomItem(<number[]> [1, 2, 3, 4, 5]); // -> 4

20、将大写字符串转换为小写

const decapitalize = (str: string): string => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;

decapitalize('Hello world'); // -> hello world

1.复制内容到剪贴板

几乎所有的网站都有存在,因为它可以让用户更方便地使用功能。但令人难以置信的是,只需要 6 行有效代码就可以做到这一点。

const copyToClipboard = (content) => {
const textarea = document.createElement("textarea")

textarea.value = content
document.body.appendChild(textarea)
textarea.select()
document.execCommand("Copy")
textarea.remove()
}

2. 比较应用程序版本

我经常遇到这个要求。如果某个APP的版本大于x.y.z,则执行A逻辑,否则执行B逻辑。

其实就是比较app版本的问题。

const compareVersion = (version1, version2) => {
const arr1 = version1.split(".")
const arr2 = version2.split(".")
const len1 = arr1.length
const len2 = arr2.length
const minLength = Math.min(len1, len2)

for (let i = 0; i < minLength; i++) {
let diff = parseInt(arr1[i], 10) - parseInt(arr2[i], 10)
if (diff !== 0) return diff
}
return len1 < len2 ? -1 : len1 > len2 ? 1 : 0
}

const v1 = '2.0.1'
const v2 = '2.1.0'
const v3 = '2.1.0'

console.log(compareVersion(v1, v2)) // -1 V1 is less than V2
console.log(compareVersion(v2, v1)) // 1 V2 is greater than v1
console.log(compareVersion(v2, v3)) // 0 V2 equals V3

3. 使用URLSearchParams获取URL的搜索参数

那是前端开发人员经常做的事情,我们通常使用正则表达式来做,但现在我们有一个更简单的方法......

const getQueryByName = (name) => {
const query = new URLSearchParams(location.search)
return decodeURIComponent(query.get(name))
}
// url: https://medium.com/?name=fatfish&age=100
const name = getQueryByName('name') // fatfish
const age = getQueryByName('age') // 100
const gender = getQueryByName('gender') // null

4. 平滑滚动到页面顶部

如何让页面平滑滚动到顶部?

Codepen地址:https://codepen.io/qianlong/pen/NWYpqZq

const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop

if (c > 0) {
window.requestAnimationFrame(scrollToTop)
window.scrollTo(0, c - c / 8)
}
}

5. 获取当前页面的滚动距离

有时候不需要平滑滚动到顶部,只需要获取滚动条滚动到多远就可以了。

const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop,
})

getScrollPosition() // { x: 0, y: 215 }

6. 判断当前设备是Android还是iOS

function getOSType() {
let u = navigator.userAgent,
app = navigator.appVersion
let isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1
let isIOS = !!u.match(/\(i[^]+( U)? CPU.+Mac OS X/)

if (isIOS) {
return 0
} else if (isAndroid) {
return 1
} else {
return 2
}
}

getOSType() // 0

7. 货币格式化

货币格式化的方式有很多种,比如这两种方式。

第一种方式:

const formatMoney = (money) => {
return money.replace(new RegExp(`(?!^)(?=(\\d{3})+${money.includes('.') ? '\\.' : '$'})`, 'g'), ',')
}

formatMoney('123456789') // '123,456,789'
formatMoney('123456789.123') // '123,456,789.123'
formatMoney('123') // '123'

第二种方式:

正则表达式让我们太头疼了,不是吗?

所以我们需要找到一种更简单的方法来格式化货币。

const formatMoney = (money) => {
return money.toLocaleString()
}

formatMoney(123456789) // '123,456,789'
formatMoney(123456789.123) // '123,456,789.123'
formatMoney(123) // '123'

我喜欢这种方式,它简单易懂。

8.进入和退出全屏

如何将网页设置为全屏模式?我在 Codepen 中写了一个小例子,Codepen:https://codepen.io/qianlong/pen/wvmJdXb

你可以试试。

// Enter full screen
function fullScreen() {
let el = document.documentElement
let rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen
//typeof rfs != "undefined" && rfs
if (rfs) {
rfs.call(el)
} else if (typeof window.ActiveXObject !== "undefined") {
let wscript = new ActiveXObject("WScript.Shell")
if (wscript != null) {
wscript.SendKeys("{F11}")
}
}
}
// Exit full screen
function exitScreen() {
let el = document
let cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen
//typeof cfs != "undefined" && cfs
if (cfs) {
cfs.call(el)
} else if (typeof window.ActiveXObject !== "undefined") {
let wscript = new ActiveXObject("WScript.Shell")
if (wscript != null) {
wscript.SendKeys("{F11}")
}
}
}