So for whatever reason the convertToArray function in the following code returns false if the argument is more than 1 character long. If it’s 1 character long it just returns the character as an array with only one value.
What I’m trying to do is take a string of numbers, plus signs, and minus signs and convert it to an array that looks like this:
Original String: 3+2-1+-2
Returned Array: 3, 2, -1, -2
And there’s probably an easier way to do this so feel free to let me know that as well haha. Anyways, here’s the code:
[CODE] function mergeValue(_sign, _value)
{
var _merged = _sign + _value;
if(_sign == “+”)
{
return _value;
}
else
{
return _merged;
}
}
function convertToArray(string)
{
if(!isValid(string))
{
//return false;
}
var newVal = new Array();
var i;
var sign = “+”;
var value = “”;
var count = 0;
for(i = 0; i < string.length; i++)
{
a = string.charAt(i – 1);
b = string.charAt(i);
if(!isNaN(b)) //IF B IS A NUMBER
{
value = value + b;
}
else if(b == “+”) //IF B IS A +
{
if(!isNaN(a))
{
newVal[count] = mergeValue(sign, value);
sign = “+”;
count = count + 1;
value = “”;
}
}
else if(b == “-“) //IF B IS A –
{
if(!isNaN(a)) // — IF A IS A NUMBER
{
newVal[count] = mergeValue(sign, value);
sign = “-“;
count = count + 1;
value = “”;
}
else if(sign == “+”) {sign = “-“;}
else if(sign == “-“) {sign = “+”;}
}
if(i == (string.length – 1))
{
newVal[count] = mergeValue(sign, value);
}
return newVal;
}