javascript - 有没有其他方法可以优化此功能或更好的方法?
问题描述
我使用 react 编写了一个函数,它按预期正常工作,我唯一的问题是是否有任何其他方法可以优化它只是为了提高可读性和更好的方法
这是我的代码:
export const formatter = (num, lastDigit = 3) => {
if (num.length === 13) {
return `xxxx xxxx xx ${num.substr(num.length - lastDigit)}`;
} else if (num.length === 14) {
return `xxxx xxxx xxx ${num.substr(num.length - lastDigit)}`;
} else {
return `xxxx xxxx xxxx ${num.substr(num.length - lastDigit)}`;
}
};
解决方案
为了更好的可读性,你可以试试这个:
export const formatter = (num, lastDigit = 3) => {
const length = num.length;
const subString = num.substr(num.length - lastDigit);
if (length === 13) {
return `xxxx xxxx xx ${subString}`;
} else if (num.length === 14) {
return `xxxx xxxx xxx ${subString}`;
} else {
return `xxxx xxxx xxxx ${subString}`;
}
};
推荐阅读
- python - Elasticsearch DSL Filter
- python - 使 ModelForm 在 Django 中与多对多关系一起工作的步骤是什么?
- c++ - 使用 C++17/20 简化模板 has_field
- hbase - Hbase shell - 查找列不存在的所有行
- javascript - 我们正在实现 Agora 屏幕共享并收到错误 DYNAMIC_USE_STATIC_KEY
- airflow - 气流 - 任务级别 end_date 不起作用
- angular - 如何在角度拖动动作期间显示单列值而不是整行
- shell - 是否有 kubectl filter 命令来获取 PVC - 它的卷 - 安装在 pod 中 - 托管在节点字段中?
- c# - C# MediateR 作为临时事件总线
- reactjs - 使用 React 在组件之间传输数据