You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中创建函数筛选作者名长度小于4的书籍?

如何在JavaScript中筛选出作者名长度小于4的书籍?

原始书籍数据

const books = [
        {
            "id": "a5b16ad1bb2e96b8c649da7150ad5726",
            "title": "Mon Oct 17 2022 21:32:42 GMT-0700 (Pacific Daylight Time)",
            "author": "Ana"
        },
        {
            "id": "221517d1a0948a2faa56a824803aa60e",
            "title": "bjlci",
            "author": "Lea Ann"
        },
        {
            "id": "286332e30d3962f5de20c2cf8b673482",
            "title": "Mon Oct 24 2022 00:38:43 GMT-0700 (Pacific Daylight Time)",
            "author": "Ana Lee"
        },
        {
            "id": "bd78bed71d601bdd19c76c8309287894",
            "title": "Mon Oct 17 2022 21:32:42 GMT-0700 (Pacific Daylight Time)",
            "author": "Lee"
        }
]

问题场景

编写的筛选函数运行时报错:TypeError: Cannot read properties of undefined (reading 'length'),错误代码如下:

function shortNameAuthors(books){
    for (let i = 0; i < books.length; i++){
        if (books["author"].length <4){
            console.log(books[i]);
        }
    }
}
console.log (shortNameAuthors(books))

错误原因

  • books是数组对象,本身没有author属性,直接写books["author"]会得到undefined,读取undefined的length就会触发报错。正确的写法应该是访问数组中当前循环的元素:books[i].author或books[i]["author"]。
  • 额外建议:为了避免部分书籍对象缺失author属性导致的报错,需要先判断author是否存在。

修正方案

方案一:修正for循环逻辑

function shortNameAuthors(books){
    const result = [];
    for (let i = 0; i < books.length; i++){
        // 先检查author是否存在,再判断长度
        if (books[i].author && books[i].author.length < 4){
            result.push(books[i]);
        }
    }
    return result;
}
// 调用函数并打印结果
console.log(shortNameAuthors(books));

方案二:使用数组filter方法(更简洁)

JavaScript数组内置的filter方法可以更高效地实现筛选逻辑:

const shortNameBooks = books.filter(book => {
    return book.author && book.author.length < 4;
});
console.log(shortNameBooks);

内容的提问来源于stack exchange,提问作者Kat Shepil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:45:34