0
votes

Comment fonctionne cet exemple Javascript fonctionnel?

Je n'arrive tout simplement pas à comprendre cet extrait de code. Pourriez-vous me donner un indice ou deux à ce sujet?

var watchList = [
                 {  
                   "Title": "Inception",
                   "Year": "2010",
                   "Rated": "PG-13",
                   "Released": "16 Jul 2010",
                   "Runtime": "148 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Christopher Nolan",
                   "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
                   "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
                   "Language": "English, Japanese, French",
                   "Country": "USA, UK",
                   "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.8",
                   "imdbVotes": "1,446,708",
                   "imdbID": "tt1375666",
                   "Type": "movie",
                   "Response": "True"
                },
                {  
                   "Title": "Interstellar",
                   "Year": "2014",
                   "Rated": "PG-13",
                   "Released": "07 Nov 2014",
                   "Runtime": "169 min",
                   "Genre": "Adventure, Drama, Sci-Fi",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan, Christopher Nolan",
                   "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
                   "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
                   "Language": "English",
                   "Country": "USA, UK",
                   "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.6",
                   "imdbVotes": "910,366",
                   "imdbID": "tt0816692",
                   "Type": "movie",
                   "Response": "True"
                },

La question: Je comprends que 'e' est le paramètre transmis au callback de la méthode map mais que sont e ["Title"] et e ["imdbRating"]? On s'attend à ce que nous exécutions cette fonction sur un tableau d'objets. Je ne comprends pas la syntaxe et comment cela peut même invoquer quelque chose. Extrêmement perplexe.

JE COMPRENDS CE QUE LE CODE FAIT MAIS COMMENT VENONS-NOUS UTILISER CE titre: e ["Title"], note: e ["imdbRating"] ???

CECI EST UN ÉCHANTILLON D'UNE TABLEAU D'OBJETS!

  var filteredList = watchList.map(function(e) {
  return {title: e["Title"], rating: e["imdbRating"]}
  }).filter((e) => e.rating >= 8);


4 commentaires

e ["Title"] accède à la propriété Title sur e . .map peut être invoqué sur des tableaux.


Comment Javascript identifie-t-il e comme objet dans le tableau?


Cela devrait aider: developer.mozilla.org/en- US / docs / Web / JavaScript / Reference /…


Et ce développeur.mozilla.org/en- US / Docs / Web / JavaScript / Référence / ...


4 Réponses :


2
votes

e est un objet avec certaines propriétés. Imaginez que cela ressemble à ceci:

  var filteredList = watchList.map(function(e) {
      return {title: e.Title, rating: e.imdbRating}
  }).filter((e) => e.rating >= 8);

donc e ["Title"] retournera 'foo' et e ["imdbRating"] retournera 7.2.

la fonction que vous avez publiée pourrait également être écrite comme ceci:

var e = {
    Title: 'foo',
    imdbRating: 7.2,
};

Peut-être que cela la rend plus facile à comprendre.


2 commentaires

Pas vraiment, ici c'est beaucoup plus complexe, ce n'est pas un objet, c'est un tableau d'objets! Si c'est le cas, comment se fait-il que rien ne soit ajouté au e pour lui montrer le chemin?


@OlegArsyonov e signifie simplement «l'élément en cours de traitement» - vous pouvez remplacer e par le nom de variable que vous choisissez - movieData, par exemple.



2
votes

Ici e pointe vers l'élément en cours de traitement dans le tableau. Donc e représentera fondamentalement chaque objet à l'intérieur du tableau. Vous pouvez remplacer e par tout autre nom valide.

Dans votre code, la première carte crée un nouveau tableau d'objets et chaque objet a deux clés title & imbRating , puis à nouveau en appliquant le filtre dessus pour créer un autre nouveau tableau où la valeur de imbRating est supérieure à 8

var watchList = [{
    "Title": "Inception",
    "Year": "2010",
    "Rated": "PG-13",
    "Released": "16 Jul 2010",
    "Runtime": "148 min",
    "Genre": "Action, Adventure, Crime",
    "Director": "Christopher Nolan",
    "Writer": "Christopher Nolan",
    "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
    "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
    "Language": "English, Japanese, French",
    "Country": "USA, UK",
    "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
    "Metascore": "74",
    "imdbRating": "8.8",
    "imdbVotes": "1,446,708",
    "imdbID": "tt1375666",
    "Type": "movie",
    "Response": "True"
  },
  {
    "Title": "Interstellar",
    "Year": "2014",
    "Rated": "PG-13",
    "Released": "07 Nov 2014",
    "Runtime": "169 min",
    "Genre": "Adventure, Drama, Sci-Fi",
    "Director": "Christopher Nolan",
    "Writer": "Jonathan Nolan, Christopher Nolan",
    "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
    "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
    "Language": "English",
    "Country": "USA, UK",
    "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
    "Metascore": "74",
    "imdbRating": "8.6",
    "imdbVotes": "910,366",
    "imdbID": "tt0816692",
    "Type": "movie",
    "Response": "True"
  }
]



var filteredList = watchList.map(function(e) {
  return {
    title: e["Title"],
    rating: e["imdbRating"]
  }
}).filter((e) => e.rating >= 8);

console.log(filteredList)


0 commentaires

1
votes
var filteredList = watchList.map(function(e) {
  return {title: e["Title"], rating: e["imdbRating"]}
  }).filter((e) => e.rating >= 8);
In the above code, the map function is used to iterate all the elements from watchList array. Map iterates all the values one by one which are objects. e is assigned the object. It returns an object with property and its value as e["Title"]. It is a way of accessing the properties of an object.e["Title"] and e.imdbRating will respectively call the values related to the title and imdbRating values. 

0 commentaires

0
votes

Séparons-le pour que cela ait plus de sens.

Tout d'abord, nous créons un nouveau tableau avec map. La carte fonctionne en itérant sur un tableau (watchList dans ce cas), à chaque itération, elle passe l'élément de tableau actuel à la fonction de rappel fournie, la valeur renvoyée définit cette valeur à l'index i dans un nouveau tableau où l'index i est la position de l'élément passé à la fonction de rappel.

Prenons par exemple:

  var filteredList = watchList.map(function(e) {
      return {title: e.Title, rating: e.imdbRating}
  }).filter((e) => e.rating >= 8);

Dans l'exemple que vous fournissez, map renvoie un nouveau tableau d'objets contenant le titre des propriétés et la note . title reste le même que celui du tableau d'origine, mais la notation est la valeur mappée de e.imdbRating.

  var filteredList = filteredList.filter((e) => e.rating >= 8);

Regardons maintenant la partie suivante. Filter, crée un nouveau tableau, en itérant sur un ancien tableau, si le rappel passé à filter renvoie true cet élément est ajouté au nouveau tableau s'il retourne false, l'élément est exclu.

Dans ce cas, la valeur finale de la liste filtrée sera un tableau d'objets avec des propriétés title et rating, où le rating est supérieur ou égal à 8;

var filteredList = watchList.map(function(e){
  return {
    title: e.title,
    rating: e.imdbRating,
  };
});

Mettons tout cela ensemble, watchList.map renvoie un nouveau tableau, et tous les tableaux ont une méthode de filtrage, donc nous pouvons enchaîner le filtre hors carte (comme ci-dessous). Enfin filter, renvoie un tableau qui sera stocké dans la variable filteredList.

const timeTwo = [1, 2, 3].map(num => num * 2);
// timesTwo = [2, 4, 6]


0 commentaires