25个javascript代码 (7个有用的javascript技巧)

9个超级好用的javascript技巧,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);

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);

这些 JavaScript 片段有助于在处理 Web 项目时节省时间并简化代码。