JavaScript: Dynamically create array -


i'm trying dynamically create array 1 in javascript. have string mathematical literal expression '2a + 3b + 4a + 5c': want split array literal part of number (ex. 'a,b,a,c').

i've tried use following code :

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(); (var = 0; < numbersarray.length; i++) {     eval('var lettersarray[' + + '] = numbersarray[' + + '].replace(/[0-9]/g,"");');     alert(eval('lettersarray[' + + ']')); } 

but doesn't work! how can fix it?

lots of errors here, tried comment of fixes:

var expression = '2a + 3b + 4a + 5c'; var numbersarray = expression.split(' + '); /* numbersarray = 2a,3b,4a,5c */  //using single quotes inside single quotes doesn't work without escaping, try double quotes instead alert("so far it's working!");  //use array literals [], not new array() unless need var lettersarray = [];  (var = 0; < numbersarray.length; i++) {     //why eval used here? , why using var re-declare lettersarray?     //eval('var lettersarray[' + + '] = numbersarray[' + + '].replace(/[0-9]/g,"");');     //alert(eval('lettersarray[' + + ']'));      //no need eval, access array indexes     lettersarray[i] = numbersarray[i].replace(/[0-9]/g, '');     alert(lettersarray[i]); } 

working example: http://jsfiddle.net/ferj5/

a quicker way accomplish same thing be:

var expression = '2a + 3b + 4a + 5c'; var letters = expression.replace(/\d+/g, '').split(' + '); //now letters == ['a', 'b', 'a', 'c'] 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -