【问题标题】:Return multiple values from array从数组中返回多个值
【发布时间】:2019-05-01 22:21:39
【问题描述】:

这是一道作业题。我需要编写一个名为“allBy”的函数,它将(艺术家)作为参数。
运行时,此函数应返回给定艺术家的“收藏”中所有记录的数组。

我编写了一个函数,它只返回一条记录,而不是多条记录。

控制台日志是向集合添加记录的功能。

 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];
       }
     }
 }

我想以数组的形式获取给定艺术家的所有记录,但我只能获取一个。我什至接近这个?

【问题讨论】:

  • 您在循环中使用return,这会停止函数中的所有操作。一旦你第一次见到你的collection[i].artist === artist,你的功能就会停止

标签: javascript arrays object ecmascript-6


【解决方案1】:

主函数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!
 }

【讨论】:

  • 哇,效果很好!非常感谢你的帮忙!!你能为我解释一下 if 语句的逻辑吗?我对 JS 还是很陌生。因此,当它找到匹配项时,会将其添加到我的数组 (collection[i].title) 的 title 属性中?
  • @JamesPaulMolnar 很高兴为您提供帮助!不确定您是否普遍询问条件,这里的if 条件来自您的代码。
  • @JamesPaulMolnar 我更新了我的答案以提示您可以在哪里添加调试。 if(collection[i].artist === artist) 条件是查看我现在正在查看的收藏的艺术家是否与我正在寻找的完全匹配。如果是,我将当前集合项的 title 添加到我的结果中。如果这不是您想要返回的内容,我建议您多玩一些并进行调试,但您已经接近了。 :)
  • 这正是我想要返回的。该代码现在运行良好。我只是想理解其中的逻辑。我知道如果条件为真,那么它会执行下一行代码。那么该函数是如何知道从收藏中的特定艺术家那里推送标题的呢? [ i ] 变量是否保存条件语句中的艺术家信息?我认为“如果”条件仅意味着对或错。那么为什么下一行代码不将所有标题[ i ] 推送到匹配项呢?如果我让这变得困难,请原谅我!
  • i 是一个索引。对于一个简单的数组 ['apple', 'banana','orange'],'apple' 在索引 0,'banana' 在索引 1,'orange' 在索引 2。源数组包含集合(带有标题的项目,作者,年份),输出数组只包含标题。
【解决方案2】:

您可以将mapfilter 一起使用:

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

【讨论】:

    猜你喜欢
    • 2014-10-12
    • 2013-08-25
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多