当前位置:网站首页>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 .

  1. “ return ” Button : Use history.back() You can create a browser “ return ” Button .
<button onclick="history.back()">
     return 
</button>     
  1. Number separator : To improve the readability of numbers , You can use underscores as separators :
const largeNumber = 1_000_000_000;

console.log(largeNumber); // 1000000000
  1. 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
});  
  1. 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 .
     Insert picture description here

  2. 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 
  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 
    }
});     
  1. Copy to clipboard , You can use Clipboard API establish “ Copy to clipboard ” function :
function copyToClipboard(text) {
    
    navigator.clipboard.writeText(text);
}       
  1. 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}`);
});    
  1. 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] 
  1. 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();     
  1. 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 :
 Insert picture description here

  1. Array weight removal
const numbers = [2, 3, 4, 4, 2];

console.log([...new Set(numbers)]); // [2, 3, 4] 
  1. Convert string to number
const str = '404';

console.log(+str) // 404; 
  1. Convert numbers to strings
const myNumber = 403;

console.log(myNumber + ''); // '403' 
  1. 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] 
  1. 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 
}     
  1. Ingenious use reduce Sum an array
const myArray = [10, 20, 30, 40];
const reducer = (total, currentValue) => total + currentValue;

console.log(myArray.reduce(reducer)); // 100 
  1. console.log() style
    Did you know that you can use CSS Statements in DevTools Set in console.log Output style :
     Insert picture description here

  2. 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>     
原网站

版权声明
本文为[C+ Ankou wood]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170516079730.html