RN Lez 02: Array, Oggetti e Funzioni
Docs: MDN JavaScript Guide
Obiettivi
Section titled “Obiettivi”- Usare map, filter, forEach, find
- Manipolare oggetti (come dict Python)
- Usare arrow functions e destrutturazione
1. Array methods
Section titled “1. Array methods”map — trasformare (list comprehension)
Section titled “map — trasformare (list comprehension)”# Pythonnumeri = [1, 2, 3, 4, 5]doppi = [n * 2 for n in numeri] # [2, 4, 6, 8, 10]// JavaScriptconst numeri = [1, 2, 3, 4, 5];const doppi = numeri.map(n => n * 2); // [2, 4, 6, 8, 10]filter — selezionare
Section titled “filter — selezionare”# Pythonmaggiori = [n for n in numeri if n > 2] # [3, 4, 5]// JavaScriptconst maggiori = numeri.filter(n => n > 2); // [3, 4, 5]forEach — ciclare
Section titled “forEach — ciclare”numeri.forEach(n => console.log(n));numeri.forEach((n, i) => console.log(`[${i}] ${n}`));find — cercare il primo
Section titled “find — cercare il primo”const prodotti = [ { nome: 'Mela', prezzo: 1.5 }, { nome: 'Pane', prezzo: 2.0 },];const trovato = prodotti.find(p => p.nome === 'Pane');// { nome: 'Pane', prezzo: 2.0 }reduce — aggregare
Section titled “reduce — aggregare”const somma = numeri.reduce((acc, n) => acc + n, 0);// 152. Oggetti (dict Python)
Section titled “2. Oggetti (dict Python)”# Pythonstudente = { "nome": "Mario", "eta": 17, "voti": [8, 7, 9]}print(studente["nome"]) # Mario// JavaScriptconst studente = { nome: 'Mario', // ← chiavi senza virgolette! eta: 17, voti: [8, 7, 9]};console.log(studente.nome); // Mario (con .)console.log(studente['eta']); // 17 (con [])Modificare
Section titled “Modificare”studente.media = 8.0; // aggiungestudente.eta = 18; // modificadelete studente.voti; // rimuove3. Destrutturazione
Section titled “3. Destrutturazione”const [x, y, z] = [10, 20, 30];// x=10, y=20, z=30
const [primo, , terzo] = [1, 2, 3];// primo=1, terzo=3Oggetti
Section titled “Oggetti”const { nome, eta } = studente;console.log(nome); // Mario
// Rinominareconst { nome: nomeStudente } = studente;
// Defaultconst { nome, cognome = 'Rossi' } = studente;Nei parametri funzione
Section titled “Nei parametri funzione”// ❌ Senza destrutturazioneconst saluta = (props) => { console.log(`Ciao ${props.nome}`);};
// ✅ Con destrutturazioneconst saluta = ({ nome, eta }) => { console.log(`Ciao ${nome}, ${eta} anni`);};4. Arrow Functions
Section titled “4. Arrow Functions”// Tradizionalefunction somma(a, b) { return a + b;}
// Arrow function (moderna ✅)const somma = (a, b) => { return a + b;};
// Arrow compatta (return implicito)const somma = (a, b) => a + b;
// Un solo parametro (parentesi optional)const doppio = x => x * 2;5. Spread Operator (...)
Section titled “5. Spread Operator (...)”const a = [1, 2, 3];const b = [4, 5, 6];const uniti = [...a, ...b]; // [1, 2, 3, 4, 5, 6]
const copia = [...a]; // copia (non riferimento!)Oggetti
Section titled “Oggetti”const base = { nome: 'Mario', eta: 17 };const completo = { ...base, classe: '4A' };// { nome: 'Mario', eta: 17, classe: '4A' }
const aggiornato = { ...base, eta: 18 };// { nome: 'Mario', eta: 18 }6. Tabella riassuntiva
Section titled “6. Tabella riassuntiva”| Operazione | Python | JavaScript |
|---|---|---|
| Trasforma | [x*2 for x in l] | l.map(x => x*2) |
| Filtra | [x for x in l if x>2] | l.filter(x => x>2) |
| Cicla | for x in l: | l.forEach(x => ...) |
| Cerca | next(x for x in l if ...) | l.find(x => ...) |
| Aggrega | sum(l) | l.reduce((a,n)=>a+n,0) |
| Lunghezza | len(l) | l.length |
| Unisci dict | {**d1, **d2} | {...o1, ...o2} |
7. Esercizio
Section titled “7. Esercizio”🎯 “Carrello della spesa”
Section titled “🎯 “Carrello della spesa””const prodotti = [ { id: 1, nome: 'Mela', prezzo: 1.20, categoria: 'Frutta' }, { id: 2, nome: 'Pane', prezzo: 2.50, categoria: 'Forno' }, { id: 3, nome: 'Latte', prezzo: 1.80, categoria: 'Latticini' }, { id: 4, nome: 'Pasta', prezzo: 1.10, categoria: 'Pasta' },];Con i dati sopra:
mapper ottenere solo i nomifilterper prodotti sotto 2€findper cercare ‘Pane’forEachper stampare “NOME: PREZZO€”reduceper il totale