如何用更简洁的ES6语法实现数据类型分类过滤(替代switch)
用ES6简化类型分类函数(替代switch)
我已经实现了一个能通过测试的filterTypes函数用来给数据分类,但不想用switch语句,有没有更简洁的ES6写法?
原函数代码:
function filterTypes(values) { const result = { number: [], string: [], object: [], others: [], }; for (const value of values) { switch (typeof value) { case "number": result.number.push(value); break; case "string": result.string.push(value); break; case "object": // null是特殊的"object"类型,需要归到others value === null ? result.others.push(value) : result.object.push(value); break; default: // undefined、bigint、symbol、boolean、function都归到others result.others.push(value); } } return result; }
方案1:类型映射表 + for...of循环
用对象存储类型到目标数组的映射逻辑,代码结构更清爽,也更容易维护:
function filterTypes(values) { const result = { number: [], string: [], object: [], others: [] }; // 定义合法类型对应的目标数组键名 const typeMap = { number: 'number', string: 'string', object: 'object' }; for (const value of values) { const type = typeof value; // 单独处理null的特殊情况 if (type === 'object' && value === null) { result.others.push(value); continue; } // 匹配到合法类型就用对应数组,否则丢进others const targetKey = typeMap[type] || 'others'; result[targetKey].push(value); } return result; }
方案2:Array.reduce一步到位(更简洁)
利用ES6的Array.reduce方法,直接遍历累加出结果,省去单独的循环声明:
function filterTypes(values) { return values.reduce((acc, value) => { const type = typeof value; // 处理null的特殊情况 if (type === 'object' && value === null) { acc.others.push(value); return acc; } // 判断当前类型是否属于预设分类,否则归到others const targetKey = ['number', 'string', 'object'].includes(type) ? type : 'others'; acc[targetKey].push(value); return acc; }, { number: [], string: [], object: [], others: [] }); // 初始化结果对象 }
补充说明
- 两种写法都完全替代了switch逻辑,后续要调整分类规则时,只需要修改映射表或预设类型数组即可,比switch更灵活。
- 必须单独处理
null是因为typeof null会返回'object',这是JavaScript的历史遗留特性。
内容的提问来源于stack exchange,提问作者user18164791
相关产品推荐
相关产品推荐

