一些强大的 Js 单行代码

2025-06-08

一些强大的 Js 单行代码

Javascript 是当今世界最强大的语言之一。在本文中,我们将介绍一些有用的 js 单行代码。

删除数组中的重复项。

const array = [12, 23, 54, 69, 4, 12, 23];
console.log(array); // [12, 23, 54, 69, 4, 12, 23]
const RemoveDuplicates = (arr) => [...new Set(arr)];
console.log(RemoveDuplicates(array)); // [12, 23, 54, 69, 4]
Enter fullscreen mode Exit fullscreen mode

生成随机 ID

const randomId = Math.random().toString(36).substring(2);
console.log(randomId); // ituzp41cq08
Enter fullscreen mode Exit fullscreen mode

随机排列数组

const alpha = ["A", "B", "C", "D", "E", "F"];
console.log(alpha); // ["A", "B", "C", "D", "E", "F"]
console.log(alpha.slice().sort(() => Math.random() - 0.5)); // ["B", "A", "C", "E", "F", "D"]
Enter fullscreen mode Exit fullscreen mode

交换两个变量

let a = 10;
let b = 5;
console.log(a, b); // 10 5

[a, b] = [b, a];
console.log(a, b); // 5 10
Enter fullscreen mode Exit fullscreen mode

分配多个变量

let [x, y, z, w] = [4, 0.5, "Ajith", ["a", "b"]];
console.log(x, y, z, w); //4 0.5 "Ajith"  ["a", "b"]
Enter fullscreen mode Exit fullscreen mode

反转字符串

const reverseString = (arr) => arr.split("").reverse().join("");
console.log(reverseString("I love to code in javascript")); //tpircsavaj ni edoc ot evol I
Enter fullscreen mode Exit fullscreen mode

合并多个数组

const languages = ["js", "c", "go", "java"];
const frameworks = ["react", "angular", "ruby on rails", "larvel"];
const combined = languages.concat(frameworks);
console.log(combined); //["js", "c", "go", "java", "react", "angular", "ruby on rails", "larvel"]
Enter fullscreen mode Exit fullscreen mode

请点赞并保存此帖子以供将来参考🚀💯

鏂囩珷鏉ユ簮锛�https://dev.to/ajithmadhan11/some-powerful-js-one-liners-600
PREV
用户身份验证,2020 年预建传统身份验证无密码身份验证社交登录实现您自己的身份验证总结更新
NEXT
科技新人,你好!试试微软这款强大的工具,轻松在 Windows 操作系统上使用 Linux