我如何在jQuery中用单词做数学



我正在尝试编写一个可以用英语单词进行数学运算的程序。

例如,我希望能够做一些类似的事情

"four thousand and three" + "seven thousand and twenty nine" 

并获得类似的输出

"eleven thousand and thirty two"

在jQuery中可以做到这一点吗?

是的,我已经编写了一个名为Word Math的jQuery插件,它正是为了这个目的而制作的。

对于您问题中的示例,您可以复制并粘贴此代码

alert($.wordMath("four thousand and three").add("seven thousand and twenty nine"));
//alerts "eleven thousand thirty two"

瞧!你做了一些单词数学运算。

Word Math还可以从Javascript数字转换为单词,反之亦然:

$.wordMath.toString(65401.90332)
// sixty five thousand four hundred one and nine tenths and three thousandths and three ten thousandths and two hundred thousandths
$.wordMath("three million four hundred and sixty seven thousand five hundred and forty two").value
// 3467542

你可以在其自述页面上阅读更多关于如何使用Word数学插件的信息

编辑:现在有一个版本的Word Math不依赖jQuery。要使用它,您应该在gitHub存储库中下载wordMath.vanilla.min.js文件,而不是wordMath.jquery.js文件。

jQuery less版本的用法与jQuery版本完全相同,只是调用中不需要$.前缀。换句话说,与其做

$.wordMath("fifteen").add("eighteen")

你会写

wordMath("fifteen").add("eighteen")

您可以使用该库,但如果您想编写自己的代码,可以从以下内容开始。

<script type="text/javascript">
var equation = "one plus two";
var arrayOfWords =  equation.split(" ");
var functionToEvaluate = "";
for(i in arrayOfWords){
    functionToEvaluate = functionToEvaluate + GetNumericOrSymbol(arrayOfWords[i]);
}
var answer = eval(functionToEvaluate);
alert(answer);
//Then your method GetNumericOrSymbol() could so something like this.
function GetNumericOrSymbol(word){
    var assocArray = new Array();
    assocArray['one'] = 1;
    assocArray['two'] = 2;
    //rest of the numbers to nine
    assocArray['plus']='+';
    //rest of your operators
    return assocArray[word];
}
</script>

把Array从函数调用中去掉会有助于优化它。写这篇文章很有趣。

正如您所知,您无法对字符串本身执行数学运算,因此您需要从将文本转换为数值开始。

对数值执行数学运算后,可以将值转换回字符串并输出结果。

最新更新