面试官:怎么实现一个对象过滤器?😅

假如你面前的是B站面试官

问:怎么实现一个函数能按指定类型过滤出数组中的对象?

我:?

一、基础实现

核心需求 :实现函数filterByType(arr, type),从数组中筛选出指定类型的元素

typescript 复制代码
function filterByType(arr, type) {
    return arr.filter(item => {
        if (type === 'array') return Array.isArray(item)
        return typeof item === type
    })
}

关键缺陷

  1. 无法正确处理nulltypeof null === 'object'
  2. 对象类型包含数组等特殊类型
  3. 缺少对现代JS类型(如Symbol)的支持

二、类型深度解析

JavaScript类型判断的复杂性体现在:

  • 原始类型undefined, boolean, number, string, bigint, symbol
  • 对象类型object, function, array, Date
  • 特殊值null(伪对象类型)

类型判断方法对比

方法 优点 缺点
typeof 快速判断原始类型 无法区分null/array
instanceof 判断构造函数 跨iframe失效
Object.prototype.toString 精确判断所有类型 需要处理返回字符串
Array.isArray 专用数组判断 仅适用于数组

什么叫跨iframe失效

在 JavaScript 中,​跨执行环境失效 特指 instanceof 等类型判断方法在不同全局作用域(如 iframe、Web Worker、Node.js 的 vm 模块等)中失效的现象。其本质原因是:​不同执行环境拥有独立的内置构造函数,导致原型链无法匹配。

三、进阶实现

typescript 复制代码
function filterByType(arr, type) {
    return arr.filter(item => {
        if (type === 'array') {
            return Array.isArray(item);
        } else if (type === 'null') {
            return item === null;
        } else if (type === 'object') {
            return item !== null && typeof item === 'object' && !Array.isArray(item);
        } else {
            return typeof item === type;
        }
    });
}

四、总结

希望能给各位大佬以后面B站的时候一点点点点点小启发

相关推荐
默_笙1 小时前
💫 闭包是个背包:拆解小米前端面试题里的三道"闭包陷阱"
前端·javascript·面试
DeepAgent2 小时前
AI Agent 入门指南(05):Agent 循环——观察、思考、行动
面试·agent
顶点多余3 小时前
9.18 面试题总结 --- 绿盟
linux·面试
尾善爱看海3 小时前
《JavaScript 数组操作全攻略:12 类 API + 30 个实战场景 + 20 个避坑指南》
前端·javascript·面试
OpsEye4 小时前
为什么你的 Agent 莫名烧钱?聊聊循环调用的兜底方案
javascript·ai编程
linux_cfan4 小时前
16 · `custom-media-element`:属性拦截与转发
前端·javascript·音视频
右耳朵猫AI4 小时前
Web前端周刊2026W38 | React 19.3 发布、StyleX 深潜、jsdom 30.1 提速
前端·javascript·react.js·typescript·node.js
落魄大学生之流水线上谋生计5 小时前
GreenLife Carbon · OpenHarmony 智慧低碳生态平台
javascript
顶点多余5 小时前
9.20 知识点查漏补缺
linux·面试·职场和发展
福兮说5 小时前
用 IndexedDB 存用户的文件,我踩过的五个坑
前端·javascript