[英]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您好,我正在尝试进行代码大战 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.我知道我所做的事情很冗长,但我想在重构之前一步一步地做。
I know this is not the final answer to the kata but I am just trying things and wondered why this did not work...我知道这不是对 kata 的最终答案,但我只是在尝试并想知道为什么这不起作用......
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.
如果您在 push 后再次检查 splitString,那么它将包含所有 11 个项目。 That is where the number 11 is coming from.
这就是数字 11 的来源。 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?
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.