首页 > 解决方案 > Javascript 输出数组中的最大值,每个数组有两个以上的值

问题描述

我有这段代码,它使用我在该行中声明的数组输出 document.write 中的最高值。这工作正常并输出最高的 56。

  function topProduct(productProfitArray) {
     if (toString.call(productProfitArray) !== "[object Array]")  
       return false;
  return Math.max.apply(null, productProfitArray);
    }

document.write(topProduct([12,34,56,1]));

现在我想在声明的数组上输出值,在 int 值旁边还有一个字符串,但我得到了Uncaught SyntaxError: Invalid or unexpected token

var productProfitArray = [ {“Product A”: -75}, {“Product B”: -70}, {“Product C”:
98}, {“Product D”: 5}, {“Product E”: -88}, {”Product F”: 29}];


 function topProduct(productProfitArray) {
     if (toString.call(productProfitArray) !== "[object Array]")  
       return false;
  return Math.max.apply(null, productProfitArray);
    }

document.write(topProduct(productProfitArray));

我尝试添加一个变量 productProfitArray,然后执行该函数,然后尝试使用 document.write 输出该变量。任何帮助,将不胜感激。

标签: javascript

解决方案


您应该映射数组以获取值:

var productProfitArray = [ {"Product A": -75}, {"Product B": -70}, {"Product C": 98}, {"Product D": 5}, {"Product E": -88}, {"Product F": 29}];

function topProduct(productProfitArray) {
  if (toString.call(productProfitArray) !== "[object Array]")  
    return false;
  return Math.max.apply(null, productProfitArray.map(o => Object.values(o)[0]));
}

document.write(topProduct(productProfitArray));


推荐阅读