简体   繁体   中英

Javascript: converting string to an array

This is one of my function for a calculator project. First I needed to convert the input string into an array, and do the operation later. (assuming that input has only numbers and '+' sign for now.

My question here is, how do I improve this code? What are the other ways to deal with this problem? (Time complexity, cleanness, shorter code.......whatever)

 function convertArray(input) { let array = []; let num = ""; for (let i = 0; i < input.length; i++) { if (input.charAt(i) == '+') { array.push(input.charAt(i)); } else { do { num += input.charAt(i); i++; } while (i < input.length && input.charAt(i) !== '+'); array.push(num); num = ""; i--; } } return array; } console.log(convertArray("10+2+3000+70+1"));

You could split with a group. this add the group as well to the array.

For other calculation signs, you could add them to the brackets.

 const convertArray = string => string.split(/([+])/); console.log(convertArray("10+2+3000+70+1"));

 const q = prompt('Sum?'); alert('Answer: ' + eval(q));

Would not recommend using eval, but if all you need is a quick and dirty trick, it works. Personally, I'd recommend a library such as Math.js, but any will do.

If you really need to do this by yourself for a project, I'd recommend checking out the answers here: Evaluating a string as a mathematical expression in JavaScript .

Hope you succeed in whatever you're planning on doing.

It seems the complexity must have something to do with your wish to determing operators. In your code you just push them all into the array. To do that is like

 const re = /((\\d+)|([^\\d]+))/g const convertArray = str => { let match, arr=[]; while (match = re.exec(str)) { arr.push(match[1]) // here you can determine if you have an operator console.log(match[1],"Operator?",!/^\\d+$/.test(match[1])) } return arr } const str = "10+2+3000+70+1"; console.log(convertArray(str));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM