Javascript Array.from ()

Il metodo statico JavaScript Array.from () crea un'istanza di Array con copia superficiale da un oggetto simile a un array o iterabile.

La sintassi del from()metodo è:

 Array.from(arraylike, mapFunc, thisArg)

Il from()metodo, essendo un metodo statico, viene chiamato utilizzando il Arraynome della classe.

da () parametri

Il from()metodo comprende:

  • arraylike - Oggetto di tipo array o iterabile da convertire in array.
  • mapFunc (opzionale) - Funzione di mappa chiamata su ogni elemento.
  • thisArg (opzionale) - Valore da usare come questo quando si esegue mapFunc.

Nota : Array.from(obj, mapFunc, thisArg)è equivalente a Array.from(obj).map(mapFunc, thisArg).

Valore restituito da da ()

  • Restituisce una nuova Arrayistanza.

Nota : questo metodo può creare array da:

  • Array-like oggetti - Gli oggetti che hanno la proprietà length e hanno elementi indicizzati come le stringhe.
  • Oggetti iterabili come Map o Set.

Esempio 1: utilizzo del metodo from ()

 // Array from String let arr1 = Array.from("abc"); console.log(arr1); // ( 'a', 'b', 'c' ) // Array from Map let mapper = new Map(( ("1", "a"), ("2", "b"), )); let arr2 = Array.from(mapper); console.log(arr2); // ( ( '1', 'a' ), ( '2', 'b' ) ) let arr3 = Array.from(mapper.keys()); console.log(arr3); // ( '1', '2' ) // Array from Set let set = new Set(("JavaScript", "Python", "Go")); let arr4 = Array.from(set); console.log(arr4); // ( 'JavaScript', 'Python', 'Go' )

Produzione

 ('a', 'b', 'c') (('1', 'a'), ('2', 'b')) ('1', '2') ('JavaScript', 'Python "," Vai ")

Funziona anche per altri oggetti iterabili.

Esempio 2: utilizzo del metodo from () con mapFunc

 function createArr(arraylike, mapFunc) ( return Array.from(arraylike, mapFunc); ) // using arrow function for mapFunc let arr1 = createArr("123456", (x) => 2 * x); console.log(arr1); // ( 2, 4, 6, 8, 10, 12 )

Produzione

 (2, 4, 6, 8, 10, 12)

Letture consigliate: JavaScript Array map ()

Articoli interessanti...