Tableau Javascript. De ()

La méthode statique JavaScript Array.from () crée une instance Array copiée superficiellement à partir d'un objet de type tableau ou itérable.

La syntaxe de la from()méthode est:

 Array.from(arraylike, mapFunc, thisArg)

La from()méthode, étant une méthode statique, est appelée en utilisant le Arraynom de la classe.

from () Paramètres

La from()méthode prend en compte:

  • arraylike - Objet de type tableau ou itérable à convertir en tableau.
  • mapFunc (facultatif) - Fonction de mappage appelée sur chaque élément.
  • thisArg (facultatif) - Valeur à utiliser comme ceci lors de l'exécution de mapFunc.

Remarque : Array.from(obj, mapFunc, thisArg)équivaut à Array.from(obj).map(mapFunc, thisArg).

Valeur renvoyée de ()

  • Renvoie une nouvelle Arrayinstance.

Remarque : cette méthode peut créer un tableau à partir de:

  • Array-like objets - Les objets qui ont la propriété length et ont des éléments indexés comme des chaînes.
  • Objets itérables comme Map ou Set.

Exemple 1: Utilisation de la méthode 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' )

Production

 ('a', 'b', 'c') (('1', 'a'), ('2', 'b')) ('1', '2') ('JavaScript', 'Python ', 'Aller' )

Cela fonctionne également pour d'autres objets itérables.

Exemple 2: Utilisation de la méthode from () avec 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 )

Production

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

Lecture recommandée: JavaScript Array map ()

Articles intéressants...