简体   繁体   English

为什么该方法将 padEnd 返回为未定义?

[英]Why the method is returning padEnd as undefined?

Using the following method, when I am entering 7.0 I get the following error:使用以下方法,当我输入7.0时,出现以下错误:

Unhandled Rejection (TypeError): Cannot read property 'padEnd' of undefined

formatInput = (value) => {
  const numsAfterDot = 6;
  const isNegative = value < 0;
  const hasDecimals = value.includes(".");
  let absolute = Math.abs(value).toString();
  if (isNaN(absolute)) return;
  else {
    const split = absolute.split(".");
    let start = hasDecimals ? split[0] : absolute.slice(0, 2);
    let rest = hasDecimals ? split[1] : absolute.slice(2, numsAfterDot)
    start = start.padStart(2, "0");
    rest = rest.padEnd(numsAfterDot, "0");
    const result = `${start}.${rest}`;
    return isNegative ? `-${result}` : result;
  }
};

Can someone please help me solve this?有人可以帮我解决这个问题吗? 错误

Expected output:预期 output:

"7.0" should converts to "07.000000"
"12" should converts to "12.000000"
".12" should converts to "00.120000"
"-123" should converts to "-12.300000"
"123456" should converts to "12.345600"

You get the error because you test to see if the string you send in has a decimal point.您收到错误是因为您测试了您发送的字符串是否有小数点。

const hasDecimals = value.includes(".");

You then convert it to absolute.然后将其转换为绝对值。

let absolute = Math.abs(value).toString();

When you do that it no longer has a decimal point, so the split is going to be ['7']当你这样做时,它不再有小数点,所以拆分将是['7']

so there is no split[1] , hence why it is undefined.所以没有split[1] ,因此它是未定义的。

Your code is a bit complicated.你的代码有点复杂。 I would just split, if it is not a length of 2, I would split the string up into two parts and then pad it.我只是拆分,如果它的长度不是 2,我会将字符串分成两部分,然后填充它。

 function custPad (str) { // convert to number const num = +str; // check if negative const neg = num < 0? '-': ''; // get rid of negative, split it at decimal const parts = Math.abs(num).toString().split('.'); // if no decimal, than break it up if (parts.length === 1) { const nums = parts[0]; // grab first two numbers parts[0] = nums.substr(0,2); // grab remaining parts[1] = nums.substr(2, 6); } // build the new string with the padding return neg + parts[0].padStart(2, '0') + "." + parts[1].padEnd(6, '0').substr(0,6); } console.log("7.0", custPad("7.0")) console.log("7", custPad("7")) console.log("0.12", custPad("0.12")); console.log("123", custPad("123")); console.log("-12", custPad("-12")); console.log("123456", custPad("123456")); console.log("12345678911111111", custPad("12345678911111111"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM