Javascript将Textarea输入转换为Array以计算平均总数



我正在尝试让脚本根据输入到文本区域的数字计算平均值。数字用逗号分隔

我要么得到了一个NaN值,要么就是工作不正常。

此代码最接近实际工作。然而,它只将逗号作为一个新元素添加,所有数字只在第一个元素中组合,将数字除以逗号的数量。

document.querySelector("#input").addEventListener("input", function test() {
const strng = document.getElementById("input").value;
var arr = strng.split(',');
const avg = arr.reduce((a, b) => a + b, 0) / arr.length;
document.getElementById("lbl").innerHTML = avg;
});

function cycle() {
var area = document.getElementById("txt").value;
var lines = area.split(',');
const average = arr => arr.reduce((a, b) => a + b, 0) / arr.length;
document.getElementById("lbl").innerHTML = average([lines]).toFixed(2);
}
setInterval(cycle, 100)
<textarea id="input"></textarea>
<label id="lbl">Result Here</label>
<textarea id="txt"></textarea>

cycle()函数在文本区域中输入第一个逗号后立即给了我一个NaN值。

有人能帮我吗?

从用户输入中分离字符串时,会得到一个字符串数组。因此,您必须将这些字符串解析为数字,并在计算之前过滤掉任何非数字值。

function test() {
const inputValue = document.getElementById("input").value;
var values = inputValue.split(',').map(v => parseFloat(v)).filter(v => !Number.isNaN(v));
const avg = values.reduce((a, b) => a + b, 0) / values.length;
document.getElementById("lbl").innerHTML = (!Number.isNaN(avg)) ? avg : '';
}
setInterval(test, 100);
<textarea id="input"></textarea><br>
<label id="lbl">Result Here</label>
<textarea id="txt"></textarea>

// access the DOM elements
const inpTxt = document.getElementById("input");
const outTxt = document.getElementById("lbl");
// add event listener to text-area "input" event
inpTxt.addEventListener("input", () => {
// collect the list of comma separated numbers into an array "numList"
const numList = inpTxt
.value                    // access the DOM element "inpTxt"'s value attribute
.split(',')               // ".split()" using "comma" as the seperator
.map(Number)              // convert each element into a number
.filter(                  // sanity check to remove any non-number data
x => !isNaN(x)
);
console.log(numList);       // to see in real-time the "numList" array on console
if (numList.length) {       // if there are any valid numbers in the array
outTxt.innerText = (      // change the "label"'s innerText
numList.reduce(         // sum the numbers in the "numList" array
(total, num) => total + num,
0                     // initialize the "sum" to zero
) /                     // divide into "numList.length" to compute average
numList.length
);
}
});
<div>
Type comma-separated numbers in below input box
and average will be calculated
</div>
<div><textarea id="input"></textarea></div>
<div><label id="lbl">Result Here</label></div>

最新更新