你必须知道的 7 个 JavaScript 单行代码

2025-05-24

你必须知道的 7 个 JavaScript 单行代码

1. 生成随机字符串
如果你需要某个东西的临时唯一 ID,那么这一
行代码将为你生成一个随机字符串

const randomString = Math.random().toString(36).slice(2);
console.log(randomString); //output- r0zf1xfqcr (the string will be random )
Enter fullscreen mode Exit fullscreen mode

2. 从电子邮件中提取域名您可以使用 substring() 方法提取 电子邮件的
域名。

let email = 'xyz@gmail.com';
le getDomain = email.substring(email.indexOf('@') + 1);

console.log(getDomain); // output - gmail.com
Enter fullscreen mode Exit fullscreen mode

3. 使用此单行代码检测暗黑模式
,您可以检查用户是否正在使用暗黑模式(然后您可以根据暗黑模式更新一些功能)

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').match;
Enter fullscreen mode Exit fullscreen mode

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 */
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

6. 重定向用户
您可以使用 JavaScript 将用户重定向到任何特定的 URL。

const redirect = url => location.href = url

/* call redirect (url) whenever you want to redirect the user to a specific url */
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/ikamran01/7-killer-javascript-one-liners-that-you-must-know-2lla
PREV
2024 年 23 个最佳 VS Code 主题 如何在 VS Code 主题中安装主题 结论
NEXT
JavaScript 中的 CJS、AMD、UMD 和 ESM 到底是什么?CJS AMD UMD ESM 摘要资源: