简体   繁体   English

从JavaScript数组中回显最大值

[英]Echo highest value from JavaScript array

I'm trying to get number from texts exist in IDs then select the highest of them and echo it in an ID HTML field, but the value will be echoed depends on the IDs' values: the code explains it more. 我试图从ID中存在的文本中获取数字,然后选择ID中最高的文本并在ID HTML字段中回显它,但是将回显的值取决于ID的值:代码将对其进行更多说明。

<script type="text/javascript">
    window.onload = function status() {
        var d = document.getElementById('mom').innerText.match(/\d+/)[0];
        var h = document.getElementById('dad').innerText.match(/\d+/)[0];
        var u = document.getElementById('sister').innerText.match(/\d+/)[0];
        var n = document.getElementById('brother').innerText.match(/\d+/)[0];
        var s = document.getElementById('none').innerText.match(/\d+/)[0];

        var res = [d, h, u, n, s];
        var largest = Math.max.apply(Math, res);

        switch (largest) {
            case 0: result = '<div>Im A</div>'; break;
            case 1: result = '<div>Im B</div>'; break;
            case 2: result = '<div>Im C</div>'; break;
            case 3: result = '<div>Im D</div>'; break;
            case 4: result = '<div>Im E</div>'; break;
        }

        document.getElementById("res").innerHTML = result ;
    }
</script>

I think, you want to retrieve index of array which has highest value and apply switch over the index. 我想,您想检索具有最高值的数组的索引并在索引上应用切换。

var res = [d, h, u, n, s];
//var largest = Math.max.apply(Math, res);
var maxValueIndex = res.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0);

switch (maxValueIndex) {
    case 0: result = '<div>Im A</div>'; break;
    case 1: result = '<div>Im B</div>'; break;
    case 2: result = '<div>Im C</div>'; break;
    case 3: result = '<div>Im D</div>'; break;
    case 4: result = '<div>Im E</div>'; break;
}
document.getElementById("res").innerHTML = result ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM