如果我有一个Math.Max对象,我该如何让它显示名称而不是数字

If I had a Math.Max object, how would I get it to display a name rather than a number?

本文关键字:显示 数字 Max Math 有一个 对象 如果      更新时间:2023-09-26

假设中有以下代码

var x = 4
var y = 6
function myFunction() {
    document.write(Math.max(x, y));
}

如果我按下一个按钮来给出Math对象的结果,我该如何让它显示6的y而不是数字本身?

if(x>y)
    document.write("x");
else
    document.write("y");

你就是这么问的吗?

如果您仍然想使用Math.max:

function myFunction() {
    if (Math.max(x, y) === x)
        document.write('x');
    else
        document.write('y');
}

您可以将名称与值相关联,例如:

var values = [
  { name: 'x', value: 4 },
  { name: 'y', value: 6 },
  { name: 'z', value: 5 }
];
function myFunction() {
  // sort the values to get the largest first
  values.sort(function(a, b){ return b.value - a.value });
  // display the name of the largest value
  document.write(values[0].name);
}