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

查看:652
本文介绍了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];

将长度除以2并使用Math.round将给您索引3而不是2,因此您需要先从长度中减去1:

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天全站免登陆