Metodi JavaScript e altro. Parte 9 Corso JavaScript da Principiante ad Avanzato in 10 post sul blog

Pubblicato: 2021-11-09

Questa è la parte 9 della serie di post sul blog JavaScript che ti porterà dal principiante all'avanzato. Questa volta esploreremo i seguenti argomenti: metodi JavaScript, valori dei parametri predefiniti, l'oggetto Date in JavaScript e la funzione freccia. Entro la fine di questa serie, conoscerai tutte le nozioni di base che devi sapere per iniziare a scrivere codice in JavaScript. Se non hai letto il precedente post del blog sugli oggetti JavaScript puoi farlo qui. Senza ulteriori indugi, iniziamo con il nono tutorial.

Metodi JavaScript e altro – sommario:

  1. Valori dei parametri predefiniti
  2. L'oggetto Date in JavaScript
  3. Metodo Map()
  4. Metodo Filter()
  5. Funzione freccia

Finora abbiamo visto molti concetti e argomenti in JavaScript, ma ce ne sono ancora alcuni comunemente usati che non abbiamo scoperto. In questo tutorial vedremo di cosa si tratta. Il primo sono i valori dei parametri predefiniti in JavaScript.

Valori dei parametri predefiniti

Le funzioni sono usate molto comunemente nella programmazione e quando qualcosa viene usato spesso non ci sono solo framework come React che sfruttano le funzioni JavaScript, ma ci sono anche ulteriori ottimizzazioni sviluppate per ottenere ancora di più dalle funzioni JavaScript. Una delle caratteristiche principali che abbiamo nelle funzioni è chiamata valori dei parametri predefiniti. I parametri predefiniti ci consentono di scrivere codici più sicuri che possono fare supposizioni sicure sull'input dell'utente. Ciò avvantaggia anche l'utente fornendo loro un'impostazione predefinita che può semplificare anche la scelta tra le loro opzioni. Vediamo alcuni esempi a riguardo.

// assume you are developing a website for a coffee shop
// and most people want to get a medium size americano
// knowing this you want to make it easir for people to
// order their coffee with less hustle
function orderCoffee(typeOfCoffee="americano", sizeOfCoffee="medium", numberOfCoffee=1){
    return (numberOfCoffee + " " + sizeOfCoffee + " size " + typeOfCoffee + " is being prepared. ");
}
console.log("Default order:");
console.log(orderCoffee());
// this way, when an average customer orders online, 
// it will be much easier for them to order their daily coffee
// so much so that they will be able to order it with a single button
// alternatively people can also customize their coffee
// by changing the inputs
console.log("Custom order:");
console.log(orderCoffee("latte", "large", 2));
console.log("Another custom order:");
console.log(orderCoffee("macchiato", "small", 1));
// it is also possible to change only part of the inputs
// and leverage the default parameters 
// for the rest of the input fields
console.log("Partially customized order:");
console.log(orderCoffee("iced coffee"));

L'esecuzione del codice sopra ci fornisce il seguente output:

javascript_methods

L'oggetto Date in JavaScript

L'oggetto Date in JavaScript è abbastanza comunemente usato, specialmente nello sviluppo web. Possiamo utilizzare l'oggetto Data per eseguire funzioni sensibili al tempo come modificare le impostazioni di visualizzazione in modalità oscura, modalità luce o qualsiasi altra modalità che l'utente potrebbe preferire. Possiamo anche utilizzare le informazioni sulla data secondo necessità all'interno del progetto su cui stiamo lavorando. Ecco alcuni esempi dell'oggetto Date in azione:

// the first step is to create a date object instance
// we cna do this by writing the following and 
// setting it to a variable or constant of our choice
let today = new Date();
console.log("We are at year: " + today.getFullYear());
console.log("We can also get month in number:");
console.log(today.getMonth());
console.log("Also we can get the hour of the day like this:");
console.log(today.getHours());
console.log("We can also get the exact minutes along with the seconds");
console.log(today.getMinutes());
console.log(today.getSeconds());
// once we have these numbers we can use them as we like
// if we want we can display them or make decisions based on them.
// if we want to display month with a name 
// rather than a number, we can also achieve that
// with the following
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
console.log("We are at the month of " + months[today.getMonth()]);
// what we just did was to create an array to store month names
// and then choose the correct month using an index value
// provided by the .getMonth() method.
// if we wanted to turn on dark mode after 8 pm,
// we could do that with the following code
// one of the first thing we should remember is that
// hours are given in the 24 hour format
// that means 8pm will mean 20 as hours
// we can also use a short hand way 
// and combine the new date object creation
// with the get hours method
let timeOfDay = new Date().getHours();
if (timeOfDay >= 20) {
    console.log("Turning on Dark Mode...");
} else {
    console.log("Do not turn on the Dark Mode");
}
// since current time is over 8pm,
// in this case we expect to get turn on Dark Mode.
// which is also the reuslt we get as we can see from
// the console output.

L'esecuzione del codice sopra ci darà i seguenti registri della console:

javascript_methods

Metodo Map()

Il metodo map è un metodo molto utile che può farti risparmiare molte righe di codice e, a seconda di come lo usi, può rendere il tuo codice molto più pulito. Sostituisce essenzialmente l'utilizzo di un ciclo for quando lo si utilizza per eseguire il ciclo su un array. Ecco alcuni esempi per il metodo map().

// lets create an array we will use for mapping
let someNumbers = [1, 2, 3, 4, 5];
// lets also create the functions we will 
// provide to the map method
function doubleNums(num1){
    return num1 * 2;
}
function squareNums(num1){
    return num1 * num1;
}
function add100(num1){
    return num1 + 100;
}
console.log("Doubled numbers array:");
console.log(someNumbers.map(doubleNums));
console.log("Squared numbers array:");
console.log(someNumbers.map(squareNums));
console.log("100 added to each of the element in the umbers array:");
console.log(someNumbers.map(add100));
// map() method will loop over each of the
// items in a given array and apply the 
// provided function
// note that we do not include paranthesis
// after the function names, this would call the function
// instead we pass the function name, 
// and map() method calls them when it needs to

L'esecuzione del codice sopra ci darà i seguenti registri della console:

javascript_methods

Metodo Filter()

Il metodo filter(), insieme al metodo map() sono entrambi metodi JavaScript piuttosto comuni. Sono molto simili al metodo map() che abbiamo appena visto. Con il metodo map() possiamo passare qualsiasi funzione e quella funzione viene applicata a ciascuno degli elementi in un array. Con il metodo filter(), passeremo in un criterio di filtro e il metodo filter eseguirà il loop su tutti gli elementi in un array e restituirà un nuovo array con solo gli elementi che soddisfano i criteri rimarranno. Vediamo alcuni esempi a riguardo:

// lets first create an array 
// to apply the filter() method
let someNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];
function checkEven(num1){
    if (num1 % 2 == 0){
        return num1;
    }
}
function checkOdd(num1){
    if (num1 % 2 == 1){
        return num1;
    }
}
function over13(num1){
    if (num1 > 13){
        return num1;
    }
}
function divisibleByFive(num){
    if (num % 5 == 0){
        return num;
    }
}
console.log("Even numbers from the list:");
console.log(someNumbers.filter(checkEven));
console.log("Odd numbers from the list:");
console.log(someNumbers.filter(checkOdd));
console.log("Numbers over 13 from the array:");
console.log(someNumbers.filter(over13));
console.log("Numbers divisible by 5 from the array:");
console.log(someNumbers.filter(divisibleByFive));
L'esecuzione del codice sopra ci darà i seguenti registri della console: javascript_methods

Funzione freccia

Ricordi quando abbiamo detto che le funzioni sono estremamente comuni in JavaScript e sono state apportate molte ottimizzazioni per ottenere un codice ancora più performante o pulito? Bene, le funzioni delle frecce sono una di queste. Le funzioni della freccia sono talvolta indicate anche come freccia grassa. Essenzialmente forniscono un modo molto più breve per scrivere le tue funzioni. Sono anche molto comunemente usati con i metodi JavaScript che abbiamo appena visto. Vediamoli con alcuni esempi:

// JavaScript provides multiple levels of 
// code shortening with arrow functions depending on your exact code
// Essantially the longest way we can write a function is 
// the way we always write them without using the arrow functions
// lets start with an array to apply the arrow functions
let someNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];
console.log("Original Array:");
console.log(someNumbers);
// in the previous examples we have applied many functions
// after creating them as regular named functions
// In this example we will apply the exact transformations
// so that you can see the both extremes in code lenght
// double every number in the array:
console.log("Double every number in the array:")
console.log(someNumbers.map(num => num * 2));
// square every number in the array:
console.log("Square every number in the array:")
console.log(someNumbers.map(num => num * num));
// add 100 to every number in the array:
console.log("Add 100 to every number in the array:")
console.log(someNumbers.map(num => num + 100));
// Only keep the even numbers in the array:
console.log("Only keep the even numbers in the array:")
console.log(someNumbers.filter(num => num % 2 == 0));
// Only keep the odd numbers in the array:
console.log("Only keep the odd numbers in the array:")
console.log(someNumbers.filter(num => num % 2 == 1));
// Only keep the numbers that are evenly divisible by 5:
console.log("Only keep the numbers that are evenly divisible by 5:")
console.log(someNumbers.filter(num => num % 5 == 0));
// Only keep the numbers that are over 13:
console.log("Only keep the numbers that are over 13:")
console.log(someNumbers.filter(num => num > 13));

L'esecuzione del codice sopra ci darà i seguenti registri della console:

javascript_methods

Nel prossimo tutorial avremo una panoramica di ciò che abbiamo visto e vedremo cosa verrà dopo.

JavaScript methods and more. Part 9 JavaScript course from Beginner to Advanced in 10 blog posts robert whitney avatar 1background

Autore: Robert Whitney

Esperto di JavaScript e istruttore che allena i dipartimenti IT. Il suo obiettivo principale è aumentare la produttività del team insegnando agli altri come cooperare efficacemente durante la programmazione.

Corso JavaScript dal principiante all'avanzato in 10 post del blog:

  1. Come iniziare a codificare in JavaScript?
  2. Nozioni di base su JavaScript
  3. Variabili e diversi tipi di dati in JavaScript
  4. Snippet e strutture di controllo
  5. While loop e for loop
  6. matrice Java
  7. Funzioni JavaScript
  8. oggetti JavaScript
  9. Metodi JavaScript e altro
  10. Riepilogo del corso JavaScript