当数字 1 或数字 2 为 NaN 或 0 时,如何隐藏/不打印/输出,只需在下面修改
document.getElementById('inputTextToSave').innerHTML = parseFloat(number1).toFixed(3) + "," + parseFloat(number2).toFixed(3);
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(",");
尝试这个条件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);
}
您可以在数组中收集值,通过检查真实性来过滤数据,并映射计算和修复。然后加入数组以获取单个字符串。如果字符串不为空,则将值分配给具有给定 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>