Reputation: 267
I want the function NumberAddition to take a string and return an array of each number in it. For example argument "abc64,$ 22, 22xyz0" should return array [64, 22, 22, 0]. The 4th line in my for loop is the problem.
It's purpose is to move i up the string after a number is indexed so that it doesn't go over the same number again. If I delete this line the rest works fine with the problem of course being the same number being counted over and over until I naturally passes over it.
Why, when this line is included, does only the first number get counted (in my example the return would be [64]). I am less interested in other ways to solve it than why this line is not functioning how I had imagined it to. Thank you!
function NumberAddition(str) {
var array = [];
var nextInt;
for(var i = 0; i < str.length; i++){
nextInt = myParseInt(str.slice(i,10));
array.push(nextInt);
if (nextInt != null)
i = str.indexOf(nextInt,i) + nextInt.length -1;
else
break;
}
// code goes here
return array;
}
function myParseInt(str){
for(var i = 0; i < str.length; i++){
if (!isNaN(str[i]))
return parseInt(str.slice(i));
}
return NaN;
}
Upvotes: -1
Views: 50
Reputation: 21505
Numbers don't have a length; strings do. nextInt.length
always returns undefined, which means you're setting i to NaN. Try nextInt.toString().length
instead.
Upvotes: 3