javascript - Javascript 计算和显示赔率作为最简单的分数
问题描述
我正在为 WooCommerce 产品页面编写一些脚本,该脚本采用在数量输入字段中输入的数量并根据该数量显示一些文本:
function reduce(numerator,denominator){
var gcd = function gcd(a,b){
return b ? gcd(b, a%b) : a;
};
gcd = gcd(numerator,denominator);
return [numerator/gcd,denominator/gcd];
}
jQuery('.qty').on('change', function() {
showOdds();
});
function showOdds() {
var qty = 1; // hard coded for testing
var min = 200; // hard coded for testing
var sofar = 40; // hard coded for testing
var plural = '';
var total = 0;
var odds = '';
if (qty > 1){
plural = 'tickets';
}
else{
plural = 'ticket';
}
if (qty > 0){
if ((qty + sofar) > min){
total = qty + sofar;
odds = reduce(qty, total);
}
else {
odds = reduce(qty, min);
}
var text = document.createElement('p');
text.className = 'product-odds';
text.innerHTML = 'Max odds of ' + qty + ' ' + plural + ' winning is ' + odds + '.';
var theDiv = document.getElementById('odds');
theDiv.appendChild(text);
}
}
jQuery(document).ready(function loadPage() {
showOdds();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='odds'></div>
当前输出:
Max odds of 1 ticket winning is 1,200
如何让赔率以最简单的分数形式显示?例如,如果有 200 张可用票并输入“1”,则应显示“1/200”,但如果有人输入“20”,则应显示“1/10”。“总”数字最终将从页面中获取,而不是固定值。
我可以使用此处发布的 gcd,但是如何从数组中获取这两个数字并将它们显示为/
所需 div 中的分数(带有 )?
解决方案
您可以返回所需的字符串而不是数组。检查下面的片段。我已经return [numerator/gcd,denominator/gcd];
改为return numerator/gcd+'/'+denominator/gcd;
function reduce(numerator,denominator){
var gcd = function gcd(a,b){
return b ? gcd(b, a%b) : a;
};
gcd = gcd(numerator,denominator);
return numerator/gcd+'/'+denominator/gcd;
}
jQuery('.qty').on('change', function() {
showOdds();
});
function showOdds() {
var qty = 1; // hard coded for testing
var min = 200; // hard coded for testing
var sofar = 40; // hard coded for testing
var plural = '';
var total = 0;
var odds = '';
if (qty > 1){
plural = 'tickets';
}
else{
plural = 'ticket';
}
if (qty > 0){
if ((qty + sofar) > min){
total = qty + sofar;
odds = reduce(qty, total);
}
else {
odds = reduce(qty, min);
}
var text = document.createElement('p');
text.className = 'product-odds';
text.innerHTML = 'Max odds of ' + qty + ' ' + plural + ' winning is ' + odds + '.';
var theDiv = document.getElementById('odds');
theDiv.appendChild(text);
}
}
jQuery(document).ready(function loadPage() {
showOdds();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='odds'></div>
推荐阅读
- c++ - ShowModal 不触发对话框的条件语句
- python-3.x - 缺失值的线性插值函数
- node.js - 如何在 Gitlab 中为 nodejs 应用程序运行测试
- c++ - 指向成员变量的指针 - C++ 中的自动类型
- javascript - openlayers 4.4:更改 wms 源的颜色和符号
- jquery - 如何实现这样的连续视差?
- javascript - ASP.Net MVC Ajax 请求触发一次,然后不再触发
- html - CSS:第一个孩子的选择器,除非在某个类的子标签中
- javascript - replace() 未按预期运行,试图在 JavaScript 中替换换行符 (/n /rn /r)
- swift - 生成包含其他数组加权平均值的数组