How can we compare three integers to find which one is bigger/smaller?

故事扮演 提交于 2019-12-11 05:02:17

问题


For example; we have three variables:

var a = 11;
var b = 23;
var c = 8;

Can we return the variable name of the biggest/smallest value?


回答1:


you probably need to use an object or an array to know the variable's name :

var obj = {
    'a':11,
    'b':23,
    'c':8
};

var biggest = '';
for (var name in obj) {
    if(biggest !== '' && obj[name] > obj[biggest]) {
        biggest = name;
    } else if (biggest === '') {
        biggest = name;
    }
}
return biggest;



回答2:


Math.max(a, b, c)

If you have variable number of items in an array:

var arr = [a, b, c];
Math.max.apply(null, arr);



回答3:


If it is the variables names of the smallest and largest values that you require, then using ECMA5 methods you could do something like this. You will need to use an object to be able to get names rather than individual variables.

Javascript

function getNamesSmallestToLargestByValue(thisObj) {
    return Object.keys(obj).map(function (name) {
        return [name, this[name]];
    }, thisObj).sort(function (x, y) {
        return x[1] - y[1];
    }).map(function (element) {
        return element.shift();
    });
}

var obj = {
        'a': 11,
        'b': 23,
        'c': 8
    };

console.log(getNamesSmallestToLargestByValue(obj));

Output

["c", "a", "b"] 

On jsFiddle

As you can see, the returned array will give you the names sorted from smallest to largest by their associated values. Therefore the first element is the name of the smallest value and last element is the name of the largest value.




回答4:


var x = parseInt(document.getElementById('sco').value);

var y = parseInt(document.getElementById('sce').value);

var z = parseInt(document.getElementById('scm').value);

if (x > y && x > z)
{
document.getElementById('yo').innerHTML = 'x is greater';
}

else if (y > x && y > z){
document.getElementById('yo').innerHTML = 'y is greater';
}

else{
document.getElementById('yo').innerHTML = 'z is greater';
}


来源:https://stackoverflow.com/questions/23547203/how-can-we-compare-three-integers-to-find-which-one-is-bigger-smaller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!