当前位置:网站首页>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>
边栏推荐
- What should I do from member labels to portraits?
- Examples of how laravel uses with preload (eager to load) and nested query
- Leetcode 78. 子集 and 90. 子集 II
- Mysql8 master-slave replication
- PHP generate order number
- 2022 edition of investment analysis and "fourteenth five year plan" development prospect forecast report of China's switchgear industry
- The transformation of enterprise customers' digital assets needs to suit the case
- How long ago did PHP get
- Laravel+gatewayworker completes the im instant messaging and file transfer functions (Chapter 4: server debugging errors)
- Scala-day05-set
猜你喜欢

【Redis 系列】redis 学习十六,redis 字典(map) 及其核心编码结构

Ctrip ticket app KMM cross end kV repository mmkv kotlin | open source

leetcode 715. Range 模块 (hard)

Vscode solves the problem of Chinese garbled code

Php+laravel5.7 use Alibaba oss+ Alibaba media to process and upload image / video files

PHP uses laravel pay component to quickly access wechat jsapi payment (wechat official account payment)

环形队列php

Microservice governance (nocas)

4. N queen problem
The loss of female scientists
随机推荐
Lintcode 130 · stacking
On the use of protostaff [easy to understand]
Scala-day06- pattern matching - Generic
证券账户一般需要在哪里开通 开户安全吗
Scala problem solving the problem of slow SBT Download
NFS共享存储服务安装
7-3 最低通行费
[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test
【毕业季·进击的技术er】忆毕业一年有感
Common problems and Thoughts on member operation management
大智慧哪个开户更安全,更好点
HUST network attack and defense practice | 6_ IOT device firmware security experiment | Experiment 3 freertos-mpu protection bypass
Ctfshow web getting started command execution web75-77
How can we reach members more effectively?
MS17_ 010 utilization summary
Laravel uses find_ IN_ The set() native MySQL statement accurately queries whether a special string exists in the specified string to solve the problem that like cannot be accurately matched. (resolve
What are the top ten securities companies? Is it safe to open a mobile account?
MOS管基本原理,单片机重要知识点
Five problems and solutions of member operation
What should I do from member labels to portraits?