簡體   English   中英

從數組返回多個值

[英]Return multiple values from array

這是一個作業問題。 我需要編寫一個名為“ allBy”的函數,該函數將(artist)作為參數。
運行時,此函數應返回給定藝術家的“收藏”中所有記錄的數組。

我編寫了一個僅返回一條記錄,但不會返回多條記錄的函數。

控制台日志是一項將記錄添加到集合的功能。

 let collection = [];

 function addToCollection( title, artist, year) {
   collection.push({title, artist, year}); // adds album to array
   return {title, artist, year};  // returns newly created object
 } // end of addToCollection function     


 console.log( addToCollection('The Real Thing', 'Faith No More', 
 1989));
 console.log( addToCollection('Angel Dust', 'Faith No More', 
 1992));
 console.log( addToCollection( 'Nevermind', 'Nirvana', 1991));
 console.log( addToCollection( 'Vulgar Display of Power', 
 'Pantera', 1991));

 function allBy(artist) {
   for ( let i = 0; i < collection.length; i++) {
   // for ( disc of collection) {
       if (collection[i].artist === artist) {
         return [collection[i].title];
       }
     }
 }

我想以數組的形式獲取給定藝術家的所有記錄,但是我只能得到一個。 我什至不對此嗎?

主函數allBy()看到第一個匹配的藝術家后立即返回。 嘗試聲明一個空數組並存儲在其中找到的匹配項,以便您可以在循環外返回該數組。

function allBy(artist) {

   var matches = []; // create an empty array to store our matches

   for ( let i = 0; i < collection.length; i++) {
       // console.log('current collection item: ', collection[i]); // optional: log or add a breakpoint here to understand what's happening on each iteration
       if (collection[i].artist === artist) {
         matches.push(collection[i].title); // add a match we've found
         // return [collection[i].title];
       }
   }

   return matches; // tada!
 }

您可以將mapfilter一起使用:

function allBy(artist) {
    return collection.filter(({ artist: a }) => a == artist).map(({ title }) => title);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM