前端常用代码整理— js,jquery篇(3)

目录

1.判断是否是json字符串

2.获取当前网址

3.将文本复制到剪贴板

4.获取一个月的天数

5.展平数组

6.要修改getRandomItem函数以返回数组中的随机两个元素,可以尝试以下代码


 

1.判断是否是json字符串
const isJson = str => {
	try {
			JSON.parse(str);
			return true;
	} catch (e) {
			return false;
	}
};
console.log(isJson('{"name":"小明","address":"苏州"}'));  //true
console.log(isJson('{"name":"小王",address:"南京"}'));   //false
2.获取当前网址
const currentURL = () => window.location.href;
currentURL()
3.将文本复制到剪贴板
const copyTextToClipboard = async (text) => {
			  await navigator.clipboard.writeText(text)
			}
			// 请注意,此函数是异步的,因为 writeText 函数返回一个 Promise。
			
			// 但是,如果您想支持 Internet Explorer 等旧版浏览器,则必须采用以下方法:此解决方案依赖于输入字段,而不是之前的基于 Promise 的解决方案。
			// HTML
			<input id="input" type="text" value="This is the text that gets copied">
			<button id="copy">Copy the text</button>
			// JavaScript
			const copy = () => {
			  const copyText = document.querySelector('#input')
			  copyText.select()
			  document.execCommand('copy')
			}
			document.querySelector('#copy').addEventListener('click', copy)
4.获取一个月的天数
const daysInMonth = (month, year) => new Date(year, month, 0).getDate()
daysInMonth(2, 2024)// 29
daysInMonth(12, 2022)// 31
5.展平数组
const flatten = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flatten(b)] : [...a, b]), [])
			flatten([[1, 2], [3, 4], [5, 6]])// [1, 2, 3, 4, 5, 6]
			flatten([["some", "text"], "and", ["some", "more"]])// ['some', 'text', 'and', 'some', 'more']
			但是还有一种更短的方法可以实现这一点。我们可以在数组上调用 flat 方法并获得相同的结果。但是,此功能尚不完全支持。尤其是在老版本的几个浏览器中,缺乏对这个功能的支持。
			[[1, 2], [3, 4], [5, 6]].flat()// [1, 2, 3, 4, 5, 6]
			[["some", "text"], "and", ["some", "more"]].flat()// ['some', 'text', 'and', 'some', 'more']
6.要修改getRandomItem函数以返回数组中的随机两个元素,可以尝试以下代码
const getRandomItems = (arr, count) => {
			    const shuffled = arr.slice().sort(() => 0.5 - Math.random());
			    return shuffled.slice(0, count);
			}
			console.log(getRandomItems([1, 7, 9, 3, 6], 2)); // [ 7, 9 ]
			console.log(getRandomItems([{ name: "Ted" }, { name: "Philip" }, { name: "Jack" }], 2)); // [ { name: 'Jack' }, { name: 'Philip' } ]
			console.log(getRandomItems([{ name: "Ted" }, 1, "Some text", 4, { name: "Jack" }], 2));

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值