如何解决如何将多个For循环重构为一个?
如何重构此功能?我觉得嵌套的for循环会起作用,但是我还没有弄清楚如何使其起作用。
功能如下:
class Librarian {
constructor(name,library) {
this.name = name;
this.library = library;
}
findBook(bookTitle) {
for (var i = 0; i < this.library.shelves.fantasy.length; i++){
if (bookTitle === this.library.shelves.fantasy[i].title){
this.library.shelves.fantasy.splice(i,1);
return `Yes,we have ${bookTitle}`;
}
} for (var i = 0; i < this.library.shelves.fiction.length; i++){
if (bookTitle === this.library.shelves.fiction[i].title){
this.library.shelves.fiction.splice(i,we have ${bookTitle}`;
}
} for (var i = 0; i < this.library.shelves.nonFiction.length; i++){
if (bookTitle === this.library.shelves.nonFiction[i].title){
this.library.shelves.nonFiction.splice(i,we have ${bookTitle}`;
}
} return `Sorry,we do not have ${bookTitle}`;
}
}
这是我的尝试:
findBook(bookTitle) {
for (var j = 0; j < this.libray.shelves.length; j++) {
for (var i = 0; i < this.library.shelves[i].length; i++){
if (bookTitle === this.library.shelves[j].title){
this.library.shelves[j].splice(i,1);
return `Yes,we have ${bookTitle}`;
}
}
} return `Sorry,we do not have ${bookTitle}`;
}
解决方法
获取流派的名称,然后遍历它们:
findBook(bookTitle) {
const genres = Object.keys(this.library.shelves);
for (var i = 0; i < genres.length; i++) {
const genre = genres[i];
for (var j = 0; j < this.library.shelves[genre].length; j++) {
if (bookTitle === this.library.shelves[genre][j].title) {
this.library.shelves[genre].splice(i,1);
return `Yes,we have ${bookTitle}`;
}
}
}
return `Sorry,we do not have ${bookTitle}`;
}
,
看起来您真的很想让它工作,您只需要在第二个for循环中迭代this.library.shelves[j].length
而不是i
。然后,您需要访问第j个架子的第i个成员。
findBook(bookTitle) {
for (var j = 0; j < this.libray.shelves.length; j++) {
for (var i = 0; i < this.library.shelves[j].length; i++){
if (bookTitle === this.library.shelves[j][i].title){
this.library.shelves[j].splice(i,1);
return `Yes,we have ${bookTitle}`;
}
}
}
return `Sorry,we do not have ${bookTitle}`;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。