大家好,欢迎来到IT知识分享网。
1.如果你需要一个临时的唯一 ID,请生成随机字符串。
这个例子将为你生成一个随机字符串:
const randomString = Math.random().toString(36).slice(2); console.log(randomString); //output- r0zf1xfqcr (the string will be random )
2. 从电子邮件中提取域名,
你可以使用 substring() 方法来提取电子邮件的域名。
let email = ''; 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
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/188250.html