mercredi 8 avril 2015

Coderbyte Number Addition - Maybe I don't understand nested if? I'm lost

I cannot figure out why I am getting ['9','9']. It seems clear to me what is happening I just don't know why.


When i = 0, the last else if statement returns true, so phrase[i+1] is returned: '9'


When i = 1, somehow the second else if is returning true. Why is this? If anything, shouldn't I get ['9',undefined]? I know I'm wrong but I'm just providing my thought process.


If you have any advice or maybe the way I'm trying to do this is bad practice or anything, I would really appreciate it. I feel so dumb I've been looking at this for a while and can't seem to figure it out on my own. =(


The other glaring issue I have with my code if anyone has some thoughts is that I realize that I am only coding for the condition that the largest values I could receive are two digit numbers. I'm sure there's a much better way to do this which would allow for any numbers and negative numbers but I I'm not sure I'm at the point I can do that yet.


Thank you



function NumberAddition(str) {
//turns string into array
var phrase = str.split("");
//creates variable storing empty array
var numbers = [];

//iterate through the array
for (var i = 0;i<phrase.length;i++){
//if two numbers in a row, concat then push value into new array, skip concat'd #
if (!(isNaN(parseInt(phrase[i]))) && !(isNaN(parseInt(phrase[i+1])))){
numbers.push(phrase[i] + phrase[i+1]);
i = i + 2;
}
//if first is a number and second is a letter, push first value
else if (!(isNaN(parseInt(phrase[i]))) && (isNaN(parseInt(phrase[i+1])))) {
numbers.push(phrase[i]);
}
//if first is not a number and second is a number, push second value
else if (!(isNaN(parseInt(phrase[i])) && (isNaN(parseInt(phrase[i+1]))))) {
numbers.push(phrase[i+1]);
}
}
//at this point, you should have all numbers in the numbers array
//fyi can add strings and get value with + infront as operator
console.log(numbers);
}
NumberAddition("f9");

Aucun commentaire:

Enregistrer un commentaire