在javascript中找到数组的中间元素 [英] finding Middle element of an array in javascript

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

问题描述

我需要编写一个程序,该程序查找数组的中间并返回存储在该数组中的值,除非该数组是偶数,否则它应该返回两个中位数的平均值.这是我到目前为止的代码.我坚持如何在偶数数组中找到中间两个数字并返回平均值.我是Java脚本的超级初学者,因此感谢所有帮助.谢谢!

I need to write a program that finds the middle of an array and returns the value stored there unless the array is even then it should return the average of the two middle most numbers. Here is the code i have so far. i'm stuck on how i would find the middle two numbers in an even array and return the average. I'm a super beginner in java script so all help is appreciated. Thanks!

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Add Ends</title>
    <script language="javascript" type="text/javascript">
      /*
      Write a function named getMiddle that returns the value of the middle element in an array. If the array has an even number of elements, then this function must return the average of the two middle elements.
      */
        var testNumbers = [0, 1 ,2, 3, 4, 5, 6, 7, 8, 9]


       function isEven()
        {
        var mid = (testNumbers[0] + (testNumbers.length)) / 2;   
        }
        
        function getMiddle(list) 
        {
            var mid = (testNumbers[0] + (testNumbers.length)) / 2;
            if (mid % 2 == 0)
                {
                var evenMid = isEven();
                document.getElementById("outputDiv1").innerHTML = evenMid;
                }
            else 
                {
                document.getElementById("outputDiv1").innerHTML = mid;
                }
        }

    </script>   
</head>

<body>
        <button type="button" onclick="binarySearch()">Find the Middle</button>
        <br>
        <div id="outputDiv1"></div>
</body>
</html>     

推荐答案

这样应该可以使您到达某个位置(来自 this SO答案):

This should get you somewhere (from this SO answer):

if (nums.length %2 == 0) {
    // even-length array (two middle elements)
    var avg = (nums[(nums.length/2) - 1] + nums[nums.length/2]) /2;
}

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

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