GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

No menu could be recovered. Follow the blue links in the page.

This view

  • Original page
  • New address

GeezerVison is showing it.javascript.info — Filter su funzioni

  • Tutorial
  • Il linguaggio JavaScript
  • Gestione avanzata delle funzioni
  • Variable scope, closure
torna alle lezioni

Filter su funzioni

importanza: 5

Abbiamo a disposizione un metodo integrato arr.filter(f) per gli array. Questo filtra tutti gli elementi attraverso la funzione f. Se ritorna true, allora quell’elemento viene ritornato.

Create un insieme di filtri “pronti all’uso”:

  • inBetween(a, b) – tra a e b o uguale.
  • inArray([...]) – contenuto nell’array.

Il loro utilizzo dovrebbe essere:

  • arr.filter(inBetween(3,6)) – seleziona solo i valori compresi tra 3 e 6.
  • arr.filter(inArray([1,2,3])) – seleziona solo gli elementi che corrispondono a [1,2,3].

Ad esempio:

/* .. your code for inBetween and inArray */
let arr = [1, 2, 3, 4, 5, 6, 7];

alert( arr.filter(inBetween(3, 6)) ); // 3,4,5,6

alert( arr.filter(inArray([1, 2, 10])) ); // 1,2

Apri una sandbox con i test.

Filter inBetween

function inBetween(a, b) {
  return function(x) {
    return x >= a && x <= b;
  };
}

let arr = [1, 2, 3, 4, 5, 6, 7];
alert( arr.filter(inBetween(3, 6)) ); // 3,4,5,6

Filter inArray

function inArray(arr) {
  return function(x) {
    return arr.includes(x);
  };
}

let arr = [1, 2, 3, 4, 5, 6, 7];
alert( arr.filter(inArray([1, 2, 10])) ); // 1,2
function inArray(arr) {
  return x => arr.includes(x);
}

function inBetween(a, b) {
  return x => (x >= a && x <= b);
}

Apri la soluzione con i test in una sandbox.

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.