我試圖讓腳本從輸入到文本區域的數字中計算平均值。數字用逗號分隔
我要么得到一個 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 值。
有人可以幫我嗎?
uj5u.com熱心網友回復:
當您從用戶輸入中拆分字串時,您會得到一個字串陣列。因此,您必須在計算之前將這些字串決議為數字并過濾掉任何非數字值。
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>
uj5u.com熱心網友回復:
// 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/466699.html
標籤:javascript 数组 平均的
下一篇:無法使用exec運行終端命令
