JS包含字符串和字符串编号的数组的平均值



我正在尝试获取包含字符串、数字和字符串数字的数组的平均值。平均数必须考虑字符串化的数字。

到目前为止,我已经使用了reduce,可以得到平均值,但无法忽略单词使其发挥作用。这就是我现在所拥有的。

<script>
function average() {
const array = [4, 45, 'hgd', '50', 87, 8, 'dhgs', 85, 4, '9'];
let sum = arr.reduce((x, y) =>
typeof +x === 'Number' ? x + y : +x + y);
sum = sum / arr.length;
return document.write(sum);
}
</script>

有人能帮我一把吗?非常感谢。

试试这个:

a.reduce((x, y) => +y ? x + +y : x)

对于平均值,你需要得到总的数组大小,你可以在reduce函数中完成:

let count = 0;
a.reduce((x, y) => {
if (+y) {
count ++;
x += +y;
}
return x;
}, 0);

正如mozilla上的开发人员所说,reduce的第二个输入是初始值,在这种情况下,我们需要为0,所以所有数组成员都进入y(如果不提供,第一个元素将被忽略(,count给出真实的结果

UPDATE 1如果您只想字符串编号,则必须使用以下内容:

let sum = a.reduce((x, y) => typeof y !== 'number' && +y ? x + +y : x, 0)

对于平均值,您需要

let count = 0;
let sum = a.reduce((x, y) => {
if (typeof y !== 'number' && +y) {
x + +y;
count ++;
}
return x;
}, 0);
let average = sum / count;

这完全符合您的预期。

您可以过滤并将数字映射到数字,同时也考虑零值,然后将所有值相加,除以数字计数的长度。

const
not = f => (...a) => !f(...a),
add = (a, b) => a + b,
array = [4, 45, 'hgd', '50', 87, 8, 'dhgs', 85, 4, '9', '1a'],
temp = array.filter(not(isNaN)).map(Number),
avg = temp.reduce(add) / temp.length;
console.log(avg);

假设您只希望实际数值的平均值过滤掉非数字字符串并减少其他

const arr = [4, 45, 'hgd', '50', 87, 8, 'dhgs', 85, 4, '9'];
const nums = arr.filter(n => !isNaN(n)).map(Number)
const ave = nums.reduce((x, y) => x + y) / (nums.length || 1);
console.log(ave)

最新更新