目 录CONTENT

文章目录

可能用到的十个超级好用的JavaScript技巧(九)

萧瑟
2023-08-07 / 0 评论 / 0 点赞 / 211 阅读 / 1,720 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2023-08-07,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

能写出优秀的代码一直是笔者所追求的,以下为笔者在开发阅读过程积累的一些代码片段以及收集了互联网上一些优秀代码片段。

1、获取字符串中的字符数

/* 可以使用它来获取空格数和随后的单词数,
* 或者这可用于获取字符串中某个分隔符的计数*/
const characterCount = (str, char) => str.split(char).length - 1

console.log(characterCount('abcadeafgahiajk', 'a'))	// 5

2、检查对象是否为空

//  我们检查对象的键的长度是否等于 0,以及传递的参数是否为实际对象
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object

console.log(isEmpty({}))	//  true
console.log(isEmpty({ not: "empty"}))	// false

3、等待一定时间后执行

// 在wait one-liner中,我们创建一个promise并在给定的时间后使用setTimeout函数解决它。
const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));

const test = async() => {
	await wait(500)
    console.log("我等待了500毫秒执行的")
}

test()	// 我等待了500毫秒执行的

4、重定向到另一个 URL

const redirect = url => location.href = url

redirect('https://www.baidu.com')

5、检查设备上的触摸支持

const touchSupported = () => ('ontouchstart' in window || DocumentTouch && document instanceof DocumentTouch)

console.log(touchSupported)

6、在元素后插入一串 HTML

const insertHTMLAfter = (html, el) => el.insertAdjacentHTML('afterend', html)

insertHTMLAfter('<p>Hi,I am Iron Man</p>', title)

7、打乱数组

const shuffle = arr => arr.sort(() => 0.5 - Math.random())

console.log(shuffle([1,2,3,4,5,6]))	// [4, 1, 6, 3, 2, 5]

8、在网页上获取选定的文本

// 鼠标选中文本,运行本函数
const getSelectedText = () => window.getSelection().toString()

console.log(getSelectedText())

9、获取一个随机布尔值

const getRandomBoolean = () => Math.random() >= 0.5

console.log(getRandomBoolean())	// true

10、计算数组的平均值

const average = (arr) => arr.reduce((a, b) => a + b) / arr.length

console.log(average([1, 2, 3, 4, 5]))	// 3

往期精彩

1、v-bind 和 v-model 的区别:你真的懂了吗?

2、你不知道的JS定时器:从原理到实践的全面指南

3、JS短路运算符的进阶:如何用它们处理复杂的逻辑和表达式


weixin

0

评论区