【问题标题】:Can't get higher order function find to work无法让高阶函数 find 工作
【发布时间】:2020-03-22 02:52:20
【问题描述】:

我是一个相当新的 webdev 学生,我目前正在做一个我们得到的练习,但我被困住了。我有一个包含对象的数组,目标是使用高阶函数来操作它们。

let bookList = [
    {
    title:"The Way of Kings",
    author: "B Sanderson",
    pages: 900,
    isAvailable:false
    },
    {
    title:"Words of radiance",
    author: "B Sanderson",
    pages: 1087,
    isAvailable:true
    },  
    {
    title:"Oathbringer",
    author: "B Sanderson",
    pages: 1000,
    isAvailable:false
    }
];

我得到了一些代码作为起点,我不允许更改。如果我的 bookList 中存在确切的标题,我应该编写一个返回 true 的函数。

function hasBook(title, bookShelf) {
}

这是我到目前为止所拥有的,我不知道如何进一步发展。在这里我得到一个错误,说 bookList 不是一个函数,但我不知道如何使它工作。我知道我搞砸了,我可能不完全理解如何使用 find 和给出的默认代码。

function hasBook(title, bookShelf) {
    if (title === bookShelf.titel) {
         return true;
    }
}

bookList.find(hasBook("Oathbringer", bookList )); 

希望你明白我在问什么。

【问题讨论】:

    标签: javascript find higher-order-functions


    【解决方案1】:

    您可以使用some 方法 - some() 方法测试数组中的至少一个元素是否通过了提供的函数实现的测试。它返回一个布尔值。

    let bookList = [
        {
        title:"The Way of Kings",
        author: "B Sanderson",
        pages: 900,
        isAvailable:false
        },
        {
        title:"Words of radiance",
        author: "B Sanderson",
        pages: 1087,
        isAvailable:true
        },
    
        {
        title:"Oathbringer",
        author: "B Sanderson",
        pages: 1000,
        isAvailable:false
        }
    ];
    
    
    function hasBook(title, bookShelf) {
    
    	return bookShelf.some((o) => o.title.toLowerCase() === title.toLowerCase());
    }
    
    console.log(hasBook('Oathbringer', bookList));

    【讨论】:

    • 哦,我不知道some() 返回了一个布尔值,这似乎是我想要的。谢谢!
    【解决方案2】:

    你可以这样做:

    function hasBook(title, bookShelf) {
        const book = bookShelf.find(book => book.title === title)
        return book ? true : false;
    }
    

    那么,你可以这样称呼它:

    const result = hasBook("Oathbringer", bookList)
    

    遵循一个完整的工作示例:

    let bookList = [
        {
        title:"The Way of Kings",
        author: "B Sanderson",
        pages: 900,
        isAvailable:false
        },
        {
        title:"Words of radiance",
        author: "B Sanderson",
        pages: 1087,
        isAvailable:true
        },
    
        {
        title:"Oathbringer",
        author: "B Sanderson",
        pages: 1000,
        isAvailable:false
        }
    ];
    
    
    function hasBook(title, bookShelf) {
        const book = bookShelf.find(book => book.title === title)
        return book ? true : false;
    }
    
    
    
    console.log(`Has book ${hasBook("Oathbringer", bookList)}`);

    【讨论】:

      猜你喜欢
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      相关资源
      最近更新 更多