two dimensional array horizontal average output

后端 未结 7 479
故里飘歌
故里飘歌 2021-01-24 05:20

I am stuck with a problem and i don\'t know how to put this in a for loop. I need the hotizontal average of the next matrix:

1 2 3 4 5

5 4 3 2 1

3 2 1 4 5


        
相关标签:
7条回答
  • 2021-01-24 06:13

    Method :

    var dArray = [[1, 2, 3, 4, 5],[5, 4, 3, 2, 1],[3, 2, 1, 4, 5]];
    alert(dArray.map(function (a) {
        return (a.reduce(function (x, y) {return (x + y);})/a.length);
    }));
    

    Implementation:

    <div id="matrix"></div>
    <script>
        var dArray = [[1, 2, 3, 4, 5],[5, 4, 3, 2, 1],[3, 2, 1, 4, 5]];
        var buffer='';
        dArray.map(function (a) {
            buffer+= a.toString()+","+ (a.reduce(function (x, y) {return (x + y);})/a.length)+"<br/>";
        });
        document.addEventListener('DOMContentLoaded',function(){
            document.getElementById('matrix').innerHTML=buffer;
        },false);
    </script>
    
    0 讨论(0)
提交回复
热议问题