【问题标题】:Javascript output the highest value on an array with more than two values each [duplicate]Javascript输出数组中的最大值,每个数组有两个以上的值[重复]
【发布时间】:2020-03-06 13:16:29
【问题描述】:

我有这段代码,它使用我在该行中声明的数组输出 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


【解决方案1】:

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

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));

【讨论】:

    猜你喜欢
    • 2017-12-20
    • 2019-02-08
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    相关资源
    最近更新 更多