Friday, 23 August 2013

JavaScript: Dynamically create array

JavaScript: Dynamically create array

I'm trying to dynamically create an array from another one in JavaScript.
I have a string which is a mathematical literal expression like this '2a +
3b + 4a + 5c': I just want to split it into an array with only the literal
part of the number (Ex. 'a,b,a,c').
I've tried to use the following code to do this :
var expression = '2a + 3b + 4a + 5c';
var NumbersArray = expression.split(' + '); /* NumbersArray = 2a,3b,4a,5c */
alert('So far it's working!');
var LettersArray = new Array();
for (var i = 0; i < NumbersArray.length; i++) {
eval('var LettersArray[' + i + '] = NumbersArray[' + i +
'].replace(/[0-9]/g,"");');
alert(eval('LettersArray[' + i + ']'));
}
But it doesn't work! How can I fix it?

No comments:

Post a Comment