【译】15 个有用的 JavaScript 技巧
2024-10-21 05:59:58
原文地址:https://javascript.plainenglish.io/15-useful-javascript-tips-814eeba1f4fd
1)数字分隔符
为了提高数字的可读性,可以使用下划线作为分隔符。
const largeNumber = 1_000_000_000;
console.log(largeNumber); // 1000000000
2)事件监听器只运行一次
如果你想添加一个事件监听器并且只运行一次,你可以使用 once 选项。
element.addEventListener('click', () => console.log('I run only once'), {
once: true
});
3)console.log变量包装器
在 console.log() 中,将参数括在花括号中,以便您可以同时看到变量名和变量值。
const name = "Maxwell";
console.log({ name });
4)检查 Caps Lock 是否打开
可以使用 KeyboardEvent.getModifierState() 来检测 Caps Lock 是否打开。
const passwordInput = document.getElementById('password');
passwordInput.addEventListener('keyup', function (event) {
if (event.getModifierState('CapsLock')) {
// CapsLock is open
}
});
5)从数组中获取最小值/最大值
可以结合扩展运算符使用 Math.min() 或 Math.max() 来查找数组中的最小值或最大值。
const numbers = [5, 7, 1, 4, 9];
console.log(Math.max(...numbers)); // 9
console.log(Math.min(...numbers)); // 1
6)获取鼠标位置
可以使用 MouseEvent 对象的 clientX 和 clientY 属性的值来获取有关当前鼠标位置坐标的信息。
document.addEventListener('mousemove', (e) => {
console.log(`Mouse X: ${e.clientX}, Mouse Y: ${e.clientY}`);
});
7)复制到剪贴板
可以使用剪贴板 API 创建“复制到剪贴板”功能。
function copyToClipboard(text) {
navigator.clipboard.writeText(text);
}
8)简写条件判断语句
如果函数只在条件为真时才执行,可以使用&&简写。
// 常规写法
if (condition) {
doSomething();
}
// 简写
condition && doSomething();
9)console.table() 以特定格式打印表格
语法:
console.table(data [, columns]);
参数:
- data 表示要显示的数据,它必须是数组或对象。
- columns 表示包含列名称的数组。
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
} const p1 = new Person("Mark", "Smith");
const p2 = new Person("Maxwell", "Siegrist");
const p3 = new Person("Lucy", "Jones");
console.table([p1, p2, p3], ["firstName"]);
10)将字符串转换为数字
const str = '508';
console.log(+str) // 508;
11)数组去重
const numbers = [2, 3, 5, 5, 2];
console.log([...new Set(numbers)]); // [2, 3, 5]
12)过滤数组中的所有假值
const myArray = [1, undefined, NaN, 2, null, '@maxwell', true, 5, false];
console.log(myArray.filter(Boolean)); // [1, 2, "@maxwell", true, 5]
13)includes() 的妙用
const myTech = 'JavaScript';
const techs = ['HTML', 'CSS', 'JavaScript'];
// 常规写法
if (myTech === 'HTML' || myTech === 'CSS' || myTech === 'JavaScript') {
// do something
}
// includes方法
if (techs.includes(myTech)) {
// do something
}
14)reduce() 的妙用
const myArray = [10, 20, 30, 40];
const reducer = (total, currentValue) => total + currentValue;
console.log(myArray.reduce(reducer)); // 100
15)元素的 dataset 属性
使用 dataset 访问元素的自定义属性(data-*)
<div id="user" data-name="Maxwell" data-age="32" data-something="Some Data">
Hello Maxwell
</div> <script>
const user = document.getElementById('user');
console.log(user.dataset); // { name: "Maxwell", age: "32", something: "Some Data" } console.log(user.dataset.name); // "Maxwell"
console.log(user.dataset.age); // "32"
console.log(user.dataset.something); // "Some Data"
</script>
最新文章
- 从0开始搭建SQL Server AlwaysOn 第一篇(配置域控)
- 101 LINQ Samples
- play 源码分析
- Struts2 Action中的方法命名不要以get开头
- 缓存池扩展 (Buffer Pool Extension)实践
- js - 犀牛学习
- .htaccess文件的详解以及404页面的设置
- Monitoring and Tuning the Linux Networking Stack: Receiving Data
- JSON的基本结构和数据交换原理
- 用于Mysql操作的MySqlHelper类
- Unable to correct problems, you have held broken packages
- js-clickNumCount.html
- Retrofit提交Json
- 1.1.8 怎样在Word的页眉中插入一级标题
- 十四. Python基础(14)--递归
- ManageEngine卓豪 IT管理峰会圆满结束
- Bitnami Redmine 中文附件名 报错修复
- C++中的类继承之单继承&;多继承&;菱形继承
- 《转载》struts旅程《1》
- java获取服务器的ip和地址
热门文章
- 如何用webgl(three.js)搭建一个3D库房,3D仓库3D码头,3D集装箱,车辆定位,叉车定位可视化孪生系统——第十五课
- .Net Core中获取appsettings.json中的节点数据
- 十九、Service Ingress
- 长文梳理muduo网络库核心代码、剖析优秀编程细节
- 2022HNCTF--WEB
- Codeforces Round #812 (Div. 2) E(并查集)
- 检测轮廓 获取其最值的坐标 opencv-python
- docker清空网络配置
- mysql如何备份
- 解决Anaconda关联VSCode使用conda运行Python报错(无法将“conda”项识别为 cmdlet、函数、脚本文件或可运行程序)