TypeScript/Angular过滤空值对象及小数保留指定位数方法问询
TypeScript/Angular 数组过滤与小数格式化解决方案
1. 对象数组空值项过滤
你现有写法的作用是过滤掉数组本身为null的成员,无法过滤对象内部属性为null的项,可根据你的需求选择对应实现:
1.1 移除指定属性为null的对象(例如删除annualRent为null的项)
直接在filter回调中判断目标属性即可,同时支持搭配类型谓词实现TS类型自动收窄:
// 定义数组项类型 interface RentItem { id: number; type?: number; startDate: string; endDate: string; endDateString?: string | null; annualRent?: string | null; endDateError?: string | null; prevEndDate?: string; useFMV?: boolean; } const originArray: RentItem[] = [ // 示例数组内容 { "id": 0, "type": 0, "startDate": "2021-09-27T16:00:00.000Z", "endDate": "2021-09-29T16:00:00.000Z", "endDateString": "09/30/2021", "annualRent": "23232", "endDateError": null }, { "id": 1, "startDate": "2021-09-27T16:00:00.000Z", "endDate": "2021-09-29T16:00:00.000Z", "endDateString": null, "annualRent": null, "prevEndDate": "2021-09-29T16:00:00.000Z", "useFMV": false } ]; // 过滤后数组仅保留annualRent不为null的项,且类型自动收窄为annualRent非空 const filteredArray = originArray.filter((item): item is RentItem & { annualRent: string } => { return item.annualRent !== null; });
1.2 移除任意属性为null的对象
如果要求对象的所有属性都不能为null才保留,可通过Object.values遍历所有属性判断:
const filteredArray = originArray.filter(item => { return Object.values(item).every(value => value !== null); });
2. 小数四舍五入保留指定位数
针对2.8333333333333335这类数值保留2位小数的需求,有两种常用稳定方案:
2.1 数值运算方案(返回数字类型)
通过放大后取整再缩小的逻辑实现,避免浮点数精度异常:
// 通用四舍五入方法,decimalPlaces为要保留的小数位数 function round(num: number, decimalPlaces: number = 2): number { const factor = Math.pow(10, decimalPlaces); return Math.round(num * factor) / factor; } // 测试 console.log(round(2.8333333333333335)) // 输出2.83 console.log(round(2.836, 2)) // 输出2.84
2.2 字符串格式化方案(适合展示场景)
如果是用于页面展示,可直接使用toFixed方法,返回格式化后的字符串,自动补全小数位:
const num = 2.8333333333333335; console.log(num.toFixed(2)) // 输出字符串"2.83" // 需要数字类型的话可以外层套Number转换 console.log(Number(num.toFixed(2))) // 输出数字2.83
内容的提问来源于stack exchange,提问作者Ananya Amar
相关产品推荐
相关产品推荐

