Maison > Java > javaDidacticiel > le corps du texte

Codes JavaScript essentiels que tout développeur devrait connaître

DDD
Libérer: 2024-10-05 18:07:02
original
672 Les gens l'ont consulté

Essential JavaScript Codes Every Developer Should Know

Essential JavaScript Codes Every Developer Should Know

JavaScript is a versatile and powerful programming language that plays a crucial role in web development. Whether you’re working on the front-end or back-end, JavaScript is key to adding interactivity, handling events, and even making network requests. Here are some essential JavaScript snippets that every developer should be familiar with.

1. Manipulating the DOM

The Document Object Model (DOM) is a representation of your HTML structure that JavaScript can manipulate. With JavaScript, you can dynamically change the content, structure, or style of your web page.


document.getElementById("demo").innerHTML = "Hello World!";


Copier après la connexion

This code finds an HTML element with the id demo and changes its content to "Hello World!".

2. Handling Events

Events such as clicks, form submissions, and key presses are integral to creating dynamic web applications.


document.getElementById("myButton").addEventListener("click", function() {
    alert("Button was clicked!");
});


Copier après la connexion

In this example, when a button with the id myButton is clicked, an alert will pop up saying "Button was clicked!".

3. Arrow Functions

Arrow functions are a more concise way to write function expressions. They also have the added benefit of not binding their own this, which is helpful in many scenarios.


const add = (a, b) => a + b;
console.log(add(5, 10)); // 15


Copier après la connexion

This code defines an arrow function add that takes two parameters and returns their sum.

4. Async/Await for Handling Promises

JavaScript is known for its asynchronous nature, and handling asynchronous operations has become easier with async and await.


async function fetchData() {
    let response = await fetch('https://api.example.com/data');
    let data = await response.json();
    console.log(data);
}


Copier après la connexion

The async keyword allows the use of await inside the function, which waits for the fetch call to complete before proceeding.

5. Local Storage for Data Persistence

Local storage allows you to store data in the user’s browser that persists even after the page is reloaded.


localStorage.setItem("username", "v2rayUser");
let user = localStorage.getItem("username");
console.log(user); // v2rayUser


Copier après la connexion

In this example, the username is saved in local storage and can be retrieved later even after the page is refreshed.

6. Destructuring Objects and Arrays

Destructuring is a convenient way to extract values from arrays or properties from objects into distinct variables.


const user = { name: 'John', age: 30 };
const { name, age } = user;
console.log(name); // John
console.log(age);  // 30


Copier après la connexion

This code demonstrates how to extract values from the user object into separate variables.

7. Map, Filter, and Reduce for Array Operations

These methods are great for manipulating and transforming arrays.

  • Map: transforms each element in an array.
  • Filter: creates a new array with elements that pass a test.
  • Reduce: applies a function to each element and reduces the array to a single value.

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
const even = numbers.filter(n => n % 2 === 0); // [2, 4]
const sum = numbers.reduce((total, n) => total + n, 0); // 15


Copier après la connexion

These methods provide a more functional approach to working with arrays, making the code easier to read and maintain.


By mastering these essential JavaScript codes, developers can write more efficient, maintainable, and effective web applications. For anyone looking to build secure and optimized VPN solutions, especially using protocols like V2Ray, check out the resources available at v2raybox.com to explore more advanced use cases and tutorials.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal