在javascript中查找数组的中间元素

时间:2016-03-28 00:26:54

标签: javascript arrays

我需要编写一个找到数组中间的程序并返回存储在那里的值,除非数组是偶数然后它应该返回两个最中间数的平均值。这是我到目前为止的代码。我坚持如何在偶数数组中找到中间两个数字并返回平均值。我是java脚本中的超级初学者,所以非常感谢所有帮助。谢谢!



<!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>     
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

这应该可以让你到达某个地方(从this SO回答):

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

答案 1 :(得分:0)

尝试以下方法:

/*
      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 output(){
            var mid = getMiddle(JSON.parse(document.getElementById("lst").value));
            outputDiv1.innerHTML = mid;
        }
        
        function getMiddle(list) 
        {
            if(list.length % 2 == 1){
                return list[(list.length-1)/2];
            }else{
                return (list[(list.length/2)]+list[(list.length/2 -1)])/2
            }
        }
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Add Ends</title>
</head>

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

答案 2 :(得分:0)

import cv2
import numpy as np

bgsMOG = cv2.BackgroundSubtractorMOG()
cap    = cv2.VideoCapture("traffic.avi")
counter = 0

if cap:
    while True:
        ret, frame = cap.read()

        if ret:            
            fgmask = bgsMOG.apply(frame, None, 0.01)
            cv2.line(frame,(0,60),(160,60),(255,255,0),1)
            # To find the countours of the Cars
            contours, hierarchy = cv2.findContours(fgmask,
                                    cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

            try:
                hierarchy = hierarchy[0]

            except:
                hierarchy = []

            for contour, hier in zip(contours, hierarchy):
                (x, y, w, h) = cv2.boundingRect(contour)

                if w > 20 and h > 20:
                    cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 1)

                    #To find centroid of the Car
                    x1 = w/2      
                    y1 = h/2

                    cx = x+x1
                    cy = y+y1
##                    print "cy=", cy
##                    print "cx=", cx
                    centroid = (cx,cy)
##                    print "centoid=", centroid
                    # Draw the circle of Centroid
                    cv2.circle(frame,(int(cx),int(cy)),2,(0,0,255),-1)

                    # To make sure the Car crosses the line
##                    dy = cy-108
##                    print "dy", dy
                    if centroid > (27, 38) and centroid < (134, 108):
##                        if (cx <= 132)and(cx >= 20):
                        counter +=1
##                            print "counter=", counter
##                    if cy > 10 and cy < 160:
                    cv2.putText(frame, str(counter), (x,y-5),
                                        cv2.FONT_HERSHEY_SIMPLEX,
                                        0.5, (255, 0, 255), 2)
##            cv2.namedWindow('Output',cv2.cv.CV_WINDOW_NORMAL)
            cv2.imshow('Output', frame)
##          cv2.imshow('FGMASK', fgmask)


            key = cv2.waitKey(60)
            if key == 27:
                break

cap.release()
cv2.destroyAllWindows()