2
votes

Comment puis-je écrire cette fonction sans utiliser de fonction fléchée?

Ceci est un exercice d'un cours. Étant donné un tableau d'objets, j'ai dû utiliser la méthode map pour faire défiler tous les éléments et retourner dans une nouvelle variable, appelée "rating", un nouveau tableau contenant uniquement la propriété Title et Rating pour chaque objet. Le tableau d'objets donné est celui-ci:

[object Object],[object Object],[object Object],[object Object],[object Object]

Le résultat final devrait être le suivant:

var rating = watchList.map(function (item){
let obj ={
   "title":item["Title"], 
    "rating":item["imdbRating"]
    }
    return obj;

Honnêtement, je ne pourrais pas vraiment trouver la solution, je l'ai cherché et j'ai trouvé celle-ci:

rating = watchList.map( (item) => ({"title":item["Title"], "rating":item["imdbRating"]}) );

Cependant, c'est une fonction de flèche que je ne comprends que partiellement, alors j'essayais de la résoudre en utilisant Règles ECMA5 et j'ai essayé ceci:

[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]

});

Mon point était, pour chaque élément que la fonction de carte effectue un cycle, il renvoie un objet dans le nouveau tableau mais montrant sur la console le résultat était:

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"
            },
            {
               "Title": "The Dark Knight",
               "Year": "2008",
               "Rated": "PG-13",
               "Released": "18 Jul 2008",
               "Runtime": "152 min",
               "Genre": "Action, Adventure, Crime",
               "Director": "Christopher Nolan",
               "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
               "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
               "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
               "Language": "English, Mandarin",
               "Country": "USA, UK",
               "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
               "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
               "Metascore": "82",
               "imdbRating": "9.0",
               "imdbVotes": "1,652,832",
               "imdbID": "tt0468569",
               "Type": "movie",
               "Response": "True"
            },
            {  
               "Title": "Batman Begins",
               "Year": "2005",
               "Rated": "PG-13",
               "Released": "15 Jun 2005",
               "Runtime": "140 min",
               "Genre": "Action, Adventure",
               "Director": "Christopher Nolan",
               "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
               "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
               "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
               "Language": "English, Urdu, Mandarin",
               "Country": "USA, UK",
               "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
               "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
               "Metascore": "70",
               "imdbRating": "8.3",
               "imdbVotes": "972,584",
               "imdbID": "tt0372784",
               "Type": "movie",
               "Response": "True"
            },
            {
               "Title": "Avatar",
               "Year": "2009",
               "Rated": "PG-13",
               "Released": "18 Dec 2009",
               "Runtime": "162 min",
               "Genre": "Action, Adventure, Fantasy",
               "Director": "James Cameron",
               "Writer": "James Cameron",
               "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
               "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
               "Language": "English, Spanish",
               "Country": "USA, UK",
               "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
               "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
               "Metascore": "83",
               "imdbRating": "7.9",
               "imdbVotes": "876,575",
               "imdbID": "tt0499549",
               "Type": "movie",
               "Response": "True"
            }];

Alors, comment puis-je écrire la fonction sans utiliser une fonction de flèche et obtenir le résultat exact?

Merci d'avance


9 commentaires

Votre fonction a l'air bien. Que se passe-t-il lorsque vous «ouvrez» l'un des objets de résultat dans le tableau via la console de débogage?


Je suis d'accord avec Pointy. Puisque vous n'utilisez que le paramètre de fonction, aucune référence à ceci ou à d'autres liaisons, l'utilisation de la notation fléchée ou de la fonction «ancienne» est équivalente ici. Le seul problème que vous rencontrez est un problème d'affichage.


Je l'ai écrit dans la dernière partie. Il me donne un tableau de [objet Object] ... mais il ne montre pas les valeurs


Quel navigateur utilisez-vous? Firefox et Chrome affichent des résultats interactifs dans la console. Vous pouvez cliquer sur les petits triangles à gauche du tableau et voir chaque valeur d'objet individuellement. La console est un outil conçu pour être utile; il ne se contente pas de vider un rendu statique brut de structures de données complexes.


il vous suffit probablement de sortir une version JSON. essayez JSON.stringify (yourResult) . Aussi, si vous faites un console.log (yourResult) , vous devriez pouvoir cliquer sur "objet objet" et voir les objets réels, s'il n'y a pas d'autre erreur. (il ne doit pas s'agir de la chaîne "objet objet"). Si vous faites cela à partir d'une console node.js à la place, ou autre, essayez d'utiliser console.log (JSON.stringify (yourResult))


Je suis d'accord avec tous les gens qui ont dit qu'il n'y a rien de mal dans votre morceau de code. Je viens de copier et coller votre code dans le violon. Vérifiez-le simplement: jsfiddle.net/5k2gbadx


Je suis sur Firefox, mais la console utilisée est celle fournie par le cours en ligne. Donc, fondamentalement, si cela ne fonctionne pas dans leur console, je ne peux pas passer le test. JSON.stringify ne fonctionne pas. Leur console devrait fonctionner correctement.


Pourquoi ne consignez-vous pas les éléments de notation un par un?


Merci à tous pour votre aide! C'était un problème avec la console. Maintenant, cela fonctionne bien et affiche même correctement le résultat en utilisant le JSON.stringify.


5 Réponses :


1
votes

Cela fonctionne parfaitement - voyez comment j'ai modifié la fonction fléchée en une fonction compatible ES5:

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"
  },
  {
    "Title": "The Dark Knight",
    "Year": "2008",
    "Rated": "PG-13",
    "Released": "18 Jul 2008",
    "Runtime": "152 min",
    "Genre": "Action, Adventure, Crime",
    "Director": "Christopher Nolan",
    "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
    "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
    "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
    "Language": "English, Mandarin",
    "Country": "USA, UK",
    "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
    "Metascore": "82",
    "imdbRating": "9.0",
    "imdbVotes": "1,652,832",
    "imdbID": "tt0468569",
    "Type": "movie",
    "Response": "True"
  },
  {
    "Title": "Batman Begins",
    "Year": "2005",
    "Rated": "PG-13",
    "Released": "15 Jun 2005",
    "Runtime": "140 min",
    "Genre": "Action, Adventure",
    "Director": "Christopher Nolan",
    "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
    "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
    "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
    "Language": "English, Urdu, Mandarin",
    "Country": "USA, UK",
    "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
    "Metascore": "70",
    "imdbRating": "8.3",
    "imdbVotes": "972,584",
    "imdbID": "tt0372784",
    "Type": "movie",
    "Response": "True"
  },
  {
    "Title": "Avatar",
    "Year": "2009",
    "Rated": "PG-13",
    "Released": "18 Dec 2009",
    "Runtime": "162 min",
    "Genre": "Action, Adventure, Fantasy",
    "Director": "James Cameron",
    "Writer": "James Cameron",
    "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
    "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
    "Language": "English, Spanish",
    "Country": "USA, UK",
    "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
    "Metascore": "83",
    "imdbRating": "7.9",
    "imdbVotes": "876,575",
    "imdbID": "tt0499549",
    "Type": "movie",
    "Response": "True"
  }
];

var ratings = watchList.map(function(item) {
  return {"Title": item["Title"], "Rating": item["imdbRating"]}
});

console.log(ratings);


0 commentaires

2
votes

Le problème pourrait être lié à la façon dont vous utilisez console.log (concaténation de chaînes avec des impressions d'objets [object Object] ).

Les deux fonctions map génèrent la même réponse. Démo ici 👇

Modifier 9j8mwo2z6p


0 commentaires

1
votes

Dans votre cas, la notation fléchée ou les mots-clés function sont équivalents pour créer une fonction. C'est parce que vous n'utilisez pas ce ou aucune liaison externe. De plus, votre syntaxe est correcte.

Notez que si vous voulez voir le contenu réel de l'objet, la manière "standard" serait de obtenir un JSON à partir de votre objet .

Vous devriez pouvoir utiliser console.log (JSON.stringify (yourObject)) , ce qui devrait vous donner ce que vous attendiez.


0 commentaires

0
votes

Le journal de la console renvoie [objet, objet] pour votre liste de surveillance car il s'agit d'un objet à l'intérieur d'un tableau, ce qui est correct au fait, j'ai essayé votre code ici en consignant la console en enregistrant la liste de surveillance et il renvoie le tableau souhaité d'un résultat de l'objet: https://es6console.com/jr72hz5j/

Si vous rencontrez des difficultés comprendre les fonctions fléchées Je vais vous aider car c'est une meilleure implémentation que la syntaxe es5:

const rating =  // the Storing of your Variable this should be constant if your don't want the data to be changed and let if you want to change it later
watchList.map( (item) => // this is equal to function(item) {} the item here is each element of your arra.
({"title":item["Title"], // this stores the object with a key of title you can also use item.Title instead
"rating":item["imdbRating"]})  // This stores the imdb rating to your new rating object you can also use item.imdbRating instead for shorter code
);

es6 peut implémenter des lignes plus courtes et peut créer une implémentation plus courte. Si vous avez des questions, répondez simplement dans les commentaires


0 commentaires

0
votes

J'ai compilé votre code d'origine pour inclure à la fois les fonctions ES5 et ES6 (les deux fonctionnent parfaitement), ainsi qu'un console.log ('ES5', ratingES5); et console.log ('ES6', ratingES6); .

Les deux consoles.logs renvoient la sortie souhaitée. Comment utilisez-vous console.log ? C'est probablement le problème.

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"
  },
  {
  "Title": "The Dark Knight",
  "Year": "2008",
  "Rated": "PG-13",
  "Released": "18 Jul 2008",
  "Runtime": "152 min",
  "Genre": "Action, Adventure, Crime",
  "Director": "Christopher Nolan",
  "Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
  "Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
  "Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
  "Language": "English, Mandarin",
  "Country": "USA, UK",
  "Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
  "Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
  "Metascore": "82",
  "imdbRating": "9.0",
  "imdbVotes": "1,652,832",
  "imdbID": "tt0468569",
  "Type": "movie",
  "Response": "True"
  },
  {  
  "Title": "Batman Begins",
  "Year": "2005",
  "Rated": "PG-13",
  "Released": "15 Jun 2005",
  "Runtime": "140 min",
  "Genre": "Action, Adventure",
  "Director": "Christopher Nolan",
  "Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
  "Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
  "Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
  "Language": "English, Urdu, Mandarin",
  "Country": "USA, UK",
  "Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
  "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
  "Metascore": "70",
  "imdbRating": "8.3",
  "imdbVotes": "972,584",
  "imdbID": "tt0372784",
  "Type": "movie",
  "Response": "True"
  },
  {
  "Title": "Avatar",
  "Year": "2009",
  "Rated": "PG-13",
  "Released": "18 Dec 2009",
  "Runtime": "162 min",
  "Genre": "Action, Adventure, Fantasy",
  "Director": "James Cameron",
  "Writer": "James Cameron",
  "Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
  "Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
  "Language": "English, Spanish",
  "Country": "USA, UK",
  "Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
  "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
  "Metascore": "83",
  "imdbRating": "7.9",
  "imdbVotes": "876,575",
  "imdbID": "tt0499549",
  "Type": "movie",
  "Response": "True"
  }
];       

let ratingES6 = watchList.map( (item) => ({"title":item["Title"], "rating":item["imdbRating"]}) );

var ratingES5 = watchList.map(function(item) {
  let obj = { "title":item["Title"], "rating":item["imdbRating"] }
  return obj;
});

console.log('ES5', ratingES5);
// [{"title":"Inception","rating":"8.8"},{"title": "Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]

console.log('ES6', ratingES6);
// logs same output above


0 commentaires