作为一名 JavaScript 开发者,你是否也曾被繁琐的代码、重复的劳动困扰?
想要更高效地开发,写出更简洁的代码,你需要掌握一些实用的技巧和工具。本文将带你领略 JavaScript 代码片段中的常见技巧,助你提升开发效率,打造更优雅的应用!
数组操作:高效处理数据集合
1. 声明和初始化数组
使用 Array(5).fill('')
可以轻松初始化一个指定大小的数组,并用默认值填充。 对于二维数组/矩阵,可以使用嵌套的 map
和 fill
方法:
const array = Array(5).fill(''); // ["", "", "", "", ""]
const matrix = Array(5).fill(0).map(() => Array(5).fill(0));
// [Array(5), Array(5), Array(5), Array(5), Array(5)]
// 0: (5) [0, 0, 0, 0, 0]
// 1: (5) [0, 0, 0, 0, 0]
// ...
// length: 5
2. 过滤数组中的假值
使用 filter(Boolean)
可以快速过滤数组中的假值(0
、undefined
、null
、false
、""
、''
):
const array = [3, 0, 6, 7, '', false];
array.filter(Boolean); // [3, 6, 7]
3. 数组查找
indexOf()
可以查找元素在数组中的位置,找不到则返回 -1
。 可以使用按位非运算符(~
) 简化判断:
if (~arr.indexOf(item)) { // 找到元素
// ...
}
if (!~arr.indexOf(item)) { // 未找到元素
// ...
}
或者使用 includes()
进行更简洁的判断:
if (arr.includes(item)) {
// ...
}
4. 洗牌数组
使用 sort()
方法结合 Math.random()
可以轻松实现洗牌:
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => Math.random() - 0.5); // 随机排序
5. 清空数组
使用 arr.length = 0
直接清空数组,而 arr = []
只是重新赋值,原来的数组仍然占用内存。
// 清空原始数组:
arr.length = 0;
// 重新赋值给一个新的空数组:
arr = [];
6. 并集、交集和差集
使用 Set
对象可以方便地进行数组的并集、交集和差集操作:
let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
// 并集
let union = new Set([...a, ...b]); // Set {1, 2, 3, 4}
// 交集
let intersect = new Set([...a].filter(x => b.has(x))); // Set {2, 3}
// 差集
let difference = new Set([...a].filter(x => !b.has(x))); // Set {1}
逻辑运算:巧妙运用条件判断
7. 使用逻辑运算符简化条件判断
使用 ||
和 &&
可以简化嵌套的 if...else
或 switch
语句:
function doSomething(arg1) {
arg1 = arg1 || 10; // 如果 arg1 未设置,则将其设置为 10
return arg1;
}
let foo = 10;
foo === 10 && doSomething(); // 输出: 10
foo === 5 || doSomething(); // 输出: 10
8. 可选链:安全访问对象属性
可选链 ?.
在访问可能为空的对象属性时,可以避免错误,返回 undefined
:
const user = { employee: { name: "Kapil" } };
user.employee?.name; // 输出: "Kapil"
user.employ?.name; // 输出: undefined
9. 空值合并运算符:提供默认值
??
运算符可以提供默认值,当左侧操作数为 null
或 undefined
时,返回右侧操作数:
const foo = null ?? 'my school'; // 输出: "my school"
const baz = 0 ?? 42; // 输出: 0
10. ||=
和 ??=
:条件赋值
||=
仅在左侧为假值时赋值,而 ??=
仅在左侧为 null
或 undefined
时赋值:
let x = null;
x ||= 5; // 输出: 5
let y = 10;
y ||= 7; // 输出: 10
let a = null;
a ??= 5; // 输出: 5
let b = 10;
b ??= 7; // 输出: 10
数字操作:灵活处理数值类型
11. 进制转换
使用 toString()
方法可以将十进制数字转换为二进制、十六进制等:
const num = 10;
num.toString(2); // 输出: "1010"
num.toString(16); // 输出: "a"
num.toString(8); // 输出: "12"
12. 获取随机整数
使用 Math.random()
和 Math.floor()
可以获取指定范围内的随机整数:
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
random(1, 50); // 返回 1 到 50 之间的随机整数
13. 字符串转数字
使用 +
或 Number()
可以快速将字符串转换为数字:
let str = '2';
console.log(Number(str)); // 2
console.log(+str); // 2
14. 科学计数法
使用科学计数法可以简洁地表示较大的数字:
for (let i = 0; i < 1e7; i++) {}
// 这些比较都返回 true
1e0 === 1;
1e1 === 10;
1e2 === 100;
// ...
对象操作:灵活处理数据结构
15. 检查对象是否为空
使用 Reflect.ownKeys()
和 constructor
属性可以判断对象是否为空:
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
isEmpty({}); // true
isEmpty({a: "not empty"}); // false
16. 动态属性名
使用方括号可以动态设置对象属性名:
const key = 'name';
const person = { [key]: 'Alice' };
console.log(person.name); // 输出: Alice
字符串操作:高效处理文本数据
17. 首字母大写
使用 charAt()
和 toUpperCase()
可以轻松实现首字母大写:
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
capitalize("hello world"); // "Hello world"
18. 反转字符串
使用 split()
、reverse()
和 join()
方法可以轻松实现字符串反转:
const reverse = str => str.split('').reverse().join('');
reverse('hello world'); // "dlrow olleh"
19. 过滤特殊字符
使用正则表达式可以方便地过滤字符串中的特殊字符:
function filterCharacter(str) {
let pattern = new RegExp("[`~!@#$^&*()=:""'。,、?|{}':;'%,\\[\\].<>/?~!@#¥……&*()&;—|{ }【】';]");
let resultStr = "";
for (let i = 0; i < str.length; i++) {
resultStr = resultStr + str.substr(i, 1).replace(pattern, '');
}
return resultStr;
}
filterCharacter('gyaskjdhy12316789#$%^&!@#1=123,./['); // "gyaskjdhy123167891123"
浏览器操作:与浏览器交互
20. 将内容复制到剪贴板
使用 navigator.clipboard.writeText()
可以将文本复制到剪贴板:
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
21. 清除所有 Cookie
使用 document.cookie
可以操作 Cookie:
const clearCookies = document.cookie.split(';').forEach(
cookie => document.cookie = cookie.replace(/^ +/, '')
.replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`)
);
22. 获取选中的文本
使用 window.getSelection().toString()
可以获取用户选中的文本:
const getSelectedText = () => window.getSelection().toString();
23. 滚动到页面顶部
使用 window.scrollTo()
可以控制页面滚动:
const goToTop = () => window.scrollTo(0, 0);
24. 检查是否滚动到底部
使用 document.documentElement.clientHeight
、window.scrollY
和 document.documentElement.scrollHeight
可以判断页面是否滚动到底部:
const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY
>= document.documentElement.scrollHeight;
25. 检查选项卡是否处于活动状态
使用 document.hidden
可以判断当前选项卡是否处于活动状态:
const isTabInView = () => !document.hidden;
26. 重定向到 URL
使用 location.href
可以进行页面重定向:
const redirect = url => location.href = url;
redirect("https://www.google.com/");
27. 打开打印对话框
使用 window.print()
可以打开打印对话框:
const showPrintDialog = () => window.print();
URL 操作:解析和处理 URL 信息
28. 从 URL 获取参数并转换为对象
使用 URL.split("?")
和 JSON.parse()
可以解析 URL 参数并转换为对象:
const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`);
getParameters("https://www.google.com.hk/search?q=js+md&newwindow=1");
// {q: 'js+md', newwindow: '1'}
其他实用技巧
29. 检查是否为函数
使用 typeof
可以判断一个对象是否为函数:
const isFunction = (obj) => typeof obj === "function" && typeof obj.nodeType !== "number" && typeof obj.item !== "function";
30. 防抖和节流
防抖: 在一段时间内只执行一次,即使触发多次事件,也只执行最后一次。
节流: 在指定时间范围内,即使触发多次事件,也只执行一次。
// 防抖
function debounce(fn, delay) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this);
}, delay);
};
}
// 节流
function throttle(fn) {
let timer = null;
return function () {
if (timer) return;
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, 1000);
};
}
31. 常见的正则表达式验证
使用正则表达式可以对常见的输入数据进行验证:
// 验证 2-9 个中文字符
const validateName = (name) => /^[\u4e00-\u9fa5]{2,9}$/.test(name);
// 验证手机号
const validatePhoneNum = (mobile) => /^1[3-9]\d{9}$/.test(mobile);
// 验证密码(6-18 个字符:字母、数字、下划线)
const validatePassword = (password) => /^[a-zA-Z0-9_]{6,18}$/.test(password);
良好的编码习惯
32. 使用解构
使用解构可以使代码更简洁:
const person = { name: "Alice", age: 25 };
const { name, age } = person;
console.log(name, age); // "Alice" 25
33. 巧妙利用 JS 隐式类型转换
使用 +
、!!
和 + ''
可以快速进行类型转换:
const price = +'32'; // 转换为数字
const isTrue = !!''; // 转换为布尔值
const str = 1 + ''; // 转换为字符串
34. 使用 return
代替 if...else
使用 return
可以简化 if...else
语句,使代码更易读:
if (condition1) {
// 执行 condition1
return;
}
if (condition2) {
// 执行 condition2
return;
}
if (condition3) {
// 执行 condition3
return;
}
总结
掌握这些 JavaScript 代码片段中的实用技巧,可以帮助你提升代码效率,写出更优雅的代码。不断学习和实践,你将发现更多提升开发效率的利器! 祝你编码愉快,创造出更精彩的应用! 😊
最后,如果这篇文章对你有所帮助,请“点赞、收藏+关注” ,感谢支持!祝您编码愉快!