当number1或number2为NaN时,如何隐藏/不打印/输出,或仅通过修改
来隐藏/输出0document.getElementById('inputTextToSave').innerHTML = parseFloat(number1).toFixed(3) + "," + parseFloat(number2).toFixed(3);
答案 0 :(得分:1)
var n1 = parseFloat(number1),
n2 = parseFloat(number2),
list = [];
// add values to array if they're not NaN or > 0
if (n1) {
list.push(n1);
}
if (n2) {
list.push(n2);
}
// combine values into a string separated with commas
document.getElementById('inputTextToSave').innerHTML = list.join(",");
答案 1 :(得分:0)
尝试此条件number1.trim()
验证NaN
并parseFloat(number1) > 0
验证0
if (number1.trim() && parseFloat(number1) > 0 && number2.trim() && parseFloat(number2) > 0) {
document.getElementById('inputTextToSave').innerHTML = parseFloat(number1).toFixed(3) + "," + parseFloat(number2).toFixed(3);
}
答案 2 :(得分:0)
您可以在数组中收集值,使用检查真实性来过滤数据并映射计算和修复。然后加入数组以获取单个字符串。如果字符串不为空,请将值赋给具有给定id的HTML元素。
function setResult(array, id) {
var result = array.filter(a => +a).map(a => (2 * a).toFixed(3)).join(', ');
if (result) {
document.getElementById(id).innerHTML = result;
}
}
setResult([0, 0], 'example0');
setResult([10], 'example1');
setResult([10, 0], 'example2');
setResult([10, 20, 30], 'example3');
<div id="example0">-</div>
<div id="example1">-</div>
<div id="example2">-</div>
<div id="example3">-</div>