简体   繁体   English

Javascript:将字符串转换为数组

[英]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.不建议使用 eval,但如果您只需要一个快速而肮脏的技巧,它就可以工作。 Personally, I'd recommend a library such as Math.js, but any will do.就个人而言,我会推荐一个库,例如 Math.js,但任何一个都可以。

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 .如果您真的需要为一个项目自己做这件事,我建议您查看这里的答案: 将字符串作为数学表达式在 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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