简体   繁体   中英

Why can I not push a number into my array of strings even though I have converted the number back to a string?

Hello there I am trying to do a code wars kata: https://www.codewars.com/kata/54a91a4883a7de5d7800009c/train/javascript

I know what I have done is very long-winded but I wanted to do it step by step before I refactored it.

  1. I have split the string input from the user
  2. Filtered through the array just to get the number and converted it to a NUMBER
  3. Incremented that number by 1
  4. Changed number back to string
  5. Now I want to add my string number to the original array but it doesn't work and I don't understand why:S

I know this is not the final answer to the kata but I am just trying things and wondered why this did not work...

function isNumeric(num){
 return !isNaN(num)
}

function incrementString (string) {
  const splitString = string.split("");

  let numbers = Number(splitString.filter(el => isNumeric(el)).join("")); //[
  'f', 'o', 'o', 'b',
  'a', 'r', '0', '0',
  '4', '2'
]

  let incrementNumber = numbers +=1; // 43

  let revertNumberToString = incrementNumber.toString(); // "43"

  let test = splitString.push(revertNumberToString); // why can I not push the number 43 onto my original array?

  console.log(test); // 11? why?

}

incrementString("foobar0042")

It does seem to be working correctly. If you check splitString again after you push to it then it will have all 11 items. That is where the number 11 is coming from. When you save a push to a variable it doesn't make a new array but rather it saves the length of the new array.

  console.log(splitString)
  // ["f", "o", "o", "b", "a", "r", "0", "0", "4", "2"]
  let test = splitString.push(revertNumberToString);
  console.log(splitString)
  // ["f", "o", "o", "b", "a", "r", "0", "0", "4", "2", 43]
  console.log(test); // 11? why?

Javascript push method adds the element to the array and returns the length, that's why you get 11 instead of the array itself. Reference

You could take a different approach by splitting the value into string and number part and take the length of the number part for later padding the value with leading zeroes.

 function incrementString(value) { const string = (value.match(/\D+/) || [''])[0], number = (value.match(/\d+/) || ['0'])[0]; return string + (+number + 1).toString().padStart(number.length, 0); } function assertEquals(a, b) { console.log(a === b, a, b); } assertEquals(incrementString("foobar000"), "foobar001"); assertEquals(incrementString("foo"), "foo1"); assertEquals(incrementString("foobar001"), "foobar002"); assertEquals(incrementString("foobar99"), "foobar100"); assertEquals(incrementString("foobar099"), "foobar100"); assertEquals(incrementString(""), "1");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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