JavaScript - 修复计算器的da * n插入符号 [英] JavaScript - Fixing that da*n caret symbol for calculator
问题描述
我正在用javascript制作计算器,截至目前它计算:
sin
, cos
, tan
, cot
, sec
,<$ c所有子类型的$ c> csc 以及 arc
和 hyberbolic
,
sqrt
, cbrt
, y-th root
,以及 POW
。问题是我不希望将 pow(x,y)
作为函数,我希望能够输入例如:
I'm making a calculator in javascript and as of now it calculates:
sin
, cos
, tan
, cot
, sec
, csc
and also arc
and hyberbolic
of all subtypes,
sqrt
, cbrt
, y-th root
, and pow
. The problem is that I dont want to have the pow(x,y)
as a function, I want to be able to type in for example:
2^3+2^4 # instead of pow(2,3)+pow(2,4)
如何获得如上所示输入的函数?以下是查看它的计算器: http://calcy.comze.com/
How do I go about to get the function typed in as shown above? Here's the calculator for viewing it: http://calcy.comze.com/
推荐答案
我假设您在字符串中有公式。以下是如何做到这一点:
I assume you have the formula in a string. Here is how you can do it:
将numbr proto扩展为 pow
方法:
Extend the numbr proto to have a pow
method:
Number.prototype.pow = function(n){
return Math.pow(this,n);
}
包围()$ c周围的每个数字$ c>并将
^
替换为 .pow()
str = str.replace(/[\d|\d.\d]+/g, function(n){
return '(' + n + ')'
})
.replace(/\^/g, '.pow')
评估字符串
eval(str)
工作示例: http:// jsbin.com/igegok/1/edit
这篇关于JavaScript - 修复计算器的da * n插入符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!