Javascript:查找数组中最中间的值 [英] Javascript: Finding the most middle value in an array

查看:41
本文介绍了Javascript:查找数组中最中间的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我需要做的是返回数组中最中间的值.我应该使用 Math.round 来计算数组中的中间索引.需要说明的是,我不是在谈论中值,而是在谈论中间值.

Okay, so what I need to do is return the most middle value in an array. And I'm supposed to use Math.round to calculate the middle index in the array. Just to be clear, I'm NOT talking about the median, just the middle value.

这就是我需要在文本中做的事情,因为我是 javascript 新手,但我不知道如何完全执行它.有什么想法吗?

That's what I need to do in text, since I'm new at javascript I don't however know how to quite execute this. Any ideas?

另外,如果你认为这个问题不属于这里或者是愚蠢的,请把我引导到可以找到这些信息的地方,我只是想在这里学习.

Also, if you think,this question doesn't belong here or is stupid, please direct me to somewhere where I can find this information, I'm just trying to learn here.

function test(arr) {


}

推荐答案

如果您有一个包含五个项目的数组,则中间项目位于索引 2 处:

If you have an array with for example five items, the middle item is at index two:

var arr = [ item, item, middle, item, item];

将长度除以二并使用 Math.round 会给你索引三而不是二,所以你需要先从长度中减去一个:

Dividing the length by two and using Math.round would give you index three rather than two, so you would need to subtract one from the length first:

var middle = arr[Math.round((arr.length - 1) / 2)];

您在问题中说您应该使用 Math.round,但如果这不是必需的,您可以使用 Math.floor:

You say in your question that you are supposed to use Math.round, but if that is not a requirement, you can get the same result easier using Math.floor:

var middle = arr[Math.floor(arr.length / 2)];

对于具有偶数个项目的数组,这将为您提供位于中间的两个项目中的第二个.如果您想要第一个,请使用 Math.floor 并从长度中减去一个.对于奇数个项目,这仍然给出相同的结果:

For an array with an even number of items, that will give you the second of the two items that are in the middle. If you want the first instead, use Math.floor and substract one from the length. That still gives the same result for odd number of items:

var middle = arr[Math.floor((arr.length - 1) / 2)];

这篇关于Javascript:查找数组中最中间的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆