使用多个数字的JavaScript中的split函数
split function in JavaScript using multiple numbers
我在理解JavaScript中的split函数时遇到了一点困难。
我正试图把运算符前后的数字求和。
我的代码如下:
else if(btnVal == '=') {
var equation = inputVal;
var lastChar = equation[equation.length - 1];
// Replace all instances of x with * respectively.
equation = equation.replace(/x/g, '*');
if (operators.indexOf(lastChar) > -1 || lastChar == ',')
equation = equation.replace(/.$/, '');
if (equation)
if (equation.indexOf('+') == 1) {
var firstNumber = equation.split('+')[0];
var secondNumber = equation.split('+')[1];
var result = Number(firstNumber) + Number(secondNumber);
input.innerHTML = result;
}
else if (equation.indexOf('*') == 1) {
firstNumber = equation.split('*')[0];
secondNumber = equation.split('*')[1];
result = Number(firstNumber) * Number(secondNumber);
input.innerHTML = result;
}
else if (equation.indexOf('-') == 1) {
firstNumber = equation.split('-')[0];
secondNumber = equation.split('-')[1];
result = Number(firstNumber) - Number(secondNumber);
input.innerHTML = result;
}
else if (equation.indexOf('/') == 1) {
firstNumber = equation.split('/')[0];
secondNumber = equation.split('/')[1];
result = Number(firstNumber) / Number(secondNumber);
input.innerHTML = result;
}
decimalAdded = false;
}
当我使用1个数字时,这一切都很好,例如1+1,但在77+8时不起作用。
有人能帮我解决这个问题吗?这样这个问题也适用于两个数字?
在输入"77+1"的情况下,以下条件是错误的
equation.indexOf('+') == 1
在上述情况下,indexOf"+"将为2,而不是1
更改该线路以及其他运营商,如下方
equation.indexOf('+') != -1
相关文章:
- javascript中的数组出错
- JavaScript中的函数和对象之间没有区别吗?
- Javascript中的空白是什么
- 为什么要使用0>javascript中的0
- 如何制作简单的php'在Javascript中的foreach等价物
- javascript中的布尔条件
- 我可以'我似乎不知道如何修复javascript中的两个lint.有人能帮我理解吗
- 验证Javascript中的Textarea
- 可以't使用Appcelerator将JSON文件解析为JavaScript中的TableView
- 是“;x==a||b”;以及“;x==a||x==b”;JavaScript中的等效语句
- 仅在IE中,javascript中的时区名称不正确
- JavaScript 中的嵌套函数和 “this” 关键字
- javascript中的命名空间,IDE中支持代码完成/内容辅助's
- JavaScript 中的高阶函数
- Javascript中的备选注释方法
- 如何使用JavaScript中的用户输入创建序列/序列
- 无法理解JavaScript中的静态方法
- 如何附加'#'到Javascript中的值
- javascript 中的全局函数
- 用javascript中的param执行动态函数