当前位置:网站首页>Several rare but useful JS techniques
Several rare but useful JS techniques
2022-06-26 12:27:00 【C+ Ankou wood】
Today, I share some rare but useful JS skill .
- “ return ” Button : Use history.back() You can create a browser “ return ” Button .
<button onclick="history.back()">
return
</button>
- Number separator : To improve the readability of numbers , You can use underscores as separators :
const largeNumber = 1_000_000_000;
console.log(largeNumber); // 1000000000
- The event listener runs only once
If you want to add an event listener and run it only once , You can use once Options :
element.addEventListener('click', () => console.log('I run only once'), {
once: true
});
console.log Variable packaging
You are in console.log() When , Enclose the parameters in curly braces , In this way, you can see the variable name and variable value at the same time .Get the minimum value from the array / Maximum
You can use Math.min() or Math.max() Combine the extension operator to find the minimum or maximum value in the array .
const numbers = [6, 8, 1, 3, 9];
console.log(Math.max(...numbers)); // 9
console.log(Math.min(...numbers)); // 1
- Check Caps Lock Whether to open
You can use KeyboardEvent.getModifierState() To see if Caps Lock open .
const passwordInput = document.getElementById('password');
passwordInput.addEventListener('keyup', function (event) {
if (event.getModifierState('CapsLock')) {
// CapsLock It's already open
}
});
- Copy to clipboard , You can use Clipboard API establish “ Copy to clipboard ” function :
function copyToClipboard(text) {
navigator.clipboard.writeText(text);
}
- Get mouse position
You can use MouseEvent Under the object clientX and clientY The attribute value , Get the current position coordinate information of the mouse .
document.addEventListener('mousemove', (e) => {
console.log(`Mouse X: ${
e.clientX}, Mouse Y: ${
e.clientY}`);
});
- Shorten array , You can set length Property to shorten the array .
const numbers = [1, 2, 3, 4, 5]
numbers.length = 3;
console.log(numbers); // [1, 2, 3]
- Short conditional judgment statement , If only the judgment condition is true The function is executed only when , You can use && Abbreviation .
// Common writing
if (condition) {
doSomething();
}
// Abbreviation
condition && doSomething();
- console.table() Print tables in a specific format
grammar :
// [] It refers to optional parameters
console.table(data [, columns]);
Parameters :
data Represents the data to be displayed . Must be an array or object .columns Represents an array containing the names of columns .
example :
// An array of objects , Print only firstName
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const john = new Person("John", "Smith");
const jane = new Person("Jane", "Doe");
const emily = new Person("Emily", "Jones");
console.table([john, jane, emily], ["firstName"]);
The printing result is shown in the figure below :
- Array weight removal
const numbers = [2, 3, 4, 4, 2];
console.log([...new Set(numbers)]); // [2, 3, 4]
- Convert string to number
const str = '404';
console.log(+str) // 404;
- Convert numbers to strings
const myNumber = 403;
console.log(myNumber + ''); // '403'
- Filter all imaginary values from the array
const myArray = [1, undefined, NaN, 2, null, '@denicmarko', true, 3, false];
console.log(myArray.filter(Boolean)); // [1, 2, "@denicmarko", true, 3]
- Ingenious use includes
const myTech = 'JavaScript';
const techs = ['HTML', 'CSS', 'JavaScript'];
// Common writing
if (myTech === 'HTML' || myTech === 'CSS' || myTech === 'JavaScript') {
// do something
}
// includes How to write it
if (techs.includes(myTech)) {
// do something
}
- Ingenious use reduce Sum an array
const myArray = [10, 20, 30, 40];
const reducer = (total, currentValue) => total + currentValue;
console.log(myArray.reduce(reducer)); // 100
console.log() style
Did you know that you can use CSS Statements in DevTools Set in console.log Output style :Elemental dataset
Use dataset Property to access the element's custom data properties (data-*):
<div id="user" data-name="John Doe" data-age="29" data-something="Some Data">
John Doe
</div>
<script>
const user = document.getElementById('user');
console.log(user.dataset);
// { name: "John Doe", age: "29", something: "Some Data" }
console.log(user.dataset.name); // "John Doe"
console.log(user.dataset.age); // "29"
console.log(user.dataset.something); // "Some Data"
</script>
边栏推荐
- Vscode solves the problem of Chinese garbled code
- One click deployment CEPH script
- TSMC Samsung will mass produce 3nm chips in 2022: will the iPhone be the first?
- Five trends of member marketing of consumer goods enterprises in the future
- Jsonarray and jsonobject of fastjson [easy to understand]
- Oracle lock table query and unlocking method
- HUST network attack and defense practice | 6_ IOT device firmware security experiment | Experiment 2 MPU based IOT device attack mitigation technology
- Scala-day06- pattern matching - Generic
- HUST network attack and defense practice | 6_ IOT device firmware security experiment | Experiment 3 freertos-mpu protection bypass
- China Medical Grade hydrogel market supply and demand research and prospect analysis report 2022 Edition
猜你喜欢
Spark-day03-core programming RDD operator
Ctrip ticket app KMM cross end kV repository mmkv kotlin | open source
2、 MySQL Foundation
HUST網絡攻防實踐|6_物聯網設備固件安全實驗|實驗二 基於 MPU 的物聯網設備攻擊緩解技術
国际美妆业巨头押注中国
This executeQuery (SQL) cannot compile classes for JSP. What is the reason?
leetcode 715. Range module (hard)
New routing file in laravel framework
HUST网络攻防实践|6_物联网设备固件安全实验|实验三 FreeRTOS-MPU 保护绕过
PHP laravel+gatewayworker completes im instant messaging and file transfer (Chapter 1: basic configuration)
随机推荐
Five trends of member management in 2022
The most complete kubernetes core command of the latest version so far
VMware virtual machine bridging mode can not access the campus network "suggestions collection"
Seven major trends deeply affecting the U.S. consumer goods industry in 2022
Fengshentai old shooting range Kali series
7-3 最低通行费
One click deployment of your own community forum
What should I do from member labels to portraits?
Loggie encoding and newline character test
菜鸟实战UML——活动图
【毕业季·进击的技术er】忆毕业一年有感
2022 China smart bathroom cabinet Market Research and investment Competitiveness Analysis Report
SQL injection in Pikachu shooting range
Hello! Forward proxy!
Current situation investigation and investment prospect forecast analysis report of China's electrolytic copper market from 2022 to 2028
Analysis report on dynamic research and investment planning suggestions of China's laser medical market in 2022
VMware虚拟机 桥接模式 无法上网 校园网「建议收藏」
JMeter response time and TPS listener tutorial
十大券商有哪些?手机开户安全么?
One click deployment CEPH script