【发布时间】: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