31个最佳 JavaScript 片段

这里有 20 个有用的 JavaScript 片段,可以在您处理项目时为您提供帮助:

1.获取当前日期和时间:

const now = new Date();

2. 检查变量是否为数组:

Array.isArray(variable);

3.合并两个数组:

const newArray = array1.concat(array2);

4. 从数组中删除重复项:

const uniqueArray = [...new Set(array)];

5. 对数组进行升序排序:

array.sort((a, b) => a - b);

6. 反转数组:

array.reverse();

7. 字符串转数字:

const number = parseInt(string, 10);

8. 生成一个介于两个值之间的随机数:

const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;

9. 检查字符串是否包含子字符串:

string.includes(substring);

10.获取一个对象的长度:

Object.keys(object).length;

11.将对象转换为数组:

const array = Object.entries(object);

12.检查对象是否为空:

Object.keys(object).length === 0 && object.constructor === Object

13.获取当前网址:

const currentUrl = window.location.href;

14. 重定向到一个新的 URL:

window.location.replace(url);

15.设置一个cookie:

document.cookie = 'name=value; expires=date; path=path; domain=domain; secure';

16. 获取 cookie:

const cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)name\s*\=\s*([^;]*).*$)|^.*$/, "$1");

17.检查cookie是否存在:

document.cookie.split(';').some((item) => item.trim().startsWith('name='))

18. 删除 cookie:

document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=path; domain=domain; secure";

19.获取当前视口尺寸:

const viewportWidth = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
const viewportHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);

20. 将文本复制到剪贴板:

navigator.clipboard.writeText(text);

21. 克隆对象

// Spread Method
let clone = { ...userDetails }

// Object.assign() Method
let clone = Object.assign({}, userDetails)

// JSON.parse() Method
let clone = JSON.parse(JSON.stringify(userDetails))

22. Array 过滤

let newArray = array.filter(item => item > 10)

23. Array遍历

let newArray = array.map(item => item + 10)

24. 查找数组中某个值

let itemWithValue10 = array.find(item => item  === 10)

25. 查找数组中某个值所在索引

let index = array.findIndex(item => item  === 10)

26. 在数组末尾添加元素

array.push(10)

27. 在数组头部添加元素

array.unshift(10)

28. 移除数组末尾元素

array.pop()

29. 移除数组头部元素

array.shift()

30. 移除数组中某位置元素

array.splice(index, 1)

31. 拷贝数组

let newArray = [...array];

ab3855d58c2750357905cdb12d315111.jpeg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值