网站首页 > 基础教程 正文
1.如果你需要一个临时的唯一 ID,请生成随机字符串。
这个例子将为你生成一个随机字符串:
const randomString = Math.random().toString(36).slice(2);
console.log(randomString); //output- r0zf1xfqcr (the string will be random )
2. 从电子邮件中提取域名,
你可以使用 substring() 方法来提取电子邮件的域名。
let email = 'xyz@gmail.com';
le getDomain = email.substring(email.indexOf('@') + 1);
console.log(getDomain); // output - gmail.com
3.用这个例子检测暗模式,你可以检查用户是否在使用暗模式(然后你可以根据暗模式更新一些功能)
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').match;
4. 检查元素是否被聚焦
在JavaScript中检测元素是否具有焦点,可以使用Document对象的只读属性activeElement。
const elem = document.querySelector(' .text-input');
const isFocus = elem == document.activeElemnt;
/* isFocus will be true if elem will have focus, and isFocus will be false if elem will not have focus */
5. 检查数组是否为空
此单行程序将让你知道数组是否为空。
let arr1 = [];
let arr2 = [2, 4, 6, 8, 10];
const arr1IsEmpty = !(Array.isArray(arr1) && arr1.length >0);
const arr2IsEmpty = !(Array.isArray(arr2) && arr2.length >0);
console.log(arr1); //output - true
console.log(arr2); // output - false
6. 重定向
你可以使用 JavaScript 将用户重定向到任何特定的 URL。
const redirect = url => location.href = url
/* call redirect (url) whenever you want to redirect the user to a specific url */
7. 检查变量是否为数组
你可以使用 Array.isArray() 方法检查任何变量是否为数组。
let fruit = 'apple';
let fruits = ["apple", "banana", "mango", "orange", "grapes"];
const isArray = (arr) => Array.isArray(arr);
console.log(isArray.(fruit)); //output - false
console.log(isArray.(fruits)), //output- true
猜你喜欢
- 2025-05-05 JS不只是简单的构造模块(读书笔记)
- 2025-05-05 黑客入门实践:如何绕过前端过滤上传文件
- 2025-05-05 sql中常用的字符串函数详解(sql字符串函数有哪些)
- 2025-05-05 js获取上传文件类型以及大小的方法
- 2025-05-05 鸿蒙上实现“翻译”功能(鸿蒙翻译怎么用)
- 2024-07-19 js中string方法(js string函数)
- 2024-07-19 前端干货:JS你必须要知道的知识 大不了重头来
- 2024-07-19 JS 前20个常用字符串方法及使用方式
- 2024-07-19 JavaScript String 对象(javascript的string对象属性及方法)
- 2024-07-19 互联网前端开发技术JavaScript字符串类型详解
- 最近发表
- 标签列表
-
- jsp (69)
- pythonlist (60)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (68)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- console.table (62)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)