首页 > 解决方案 > 有没有其他方法可以优化此功能或更好的方法?

问题描述

我使用 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)}`;
  }
};

标签: javascriptreactjs

解决方案


为了更好的可读性,你可以试试这个:

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}`;
  }
};

推荐阅读