javascript - 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 输出该变量。任何帮助,将不胜感激。
解决方案
您应该映射数组以获取值:
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));
推荐阅读
- javascript - 使用 Gatsby v3 (css-loader v5) 在 CSS 类名中添加破折号
- slack - Slack 命令请求正文模式可以保持不变吗?
- c# - 将 docker-compose 输出重定向到 C# 控制台应用程序
- angular - Angular http 通过 404 获取现有且正确的 URL !!!来自 json 服务器
- css - 从 set 属性中减去值
- mysql - 如何在同一数据库上测试 2 个补丁/post api 调用的响应
- c++ - 空指针解引用
- c - 就 Big O 而言,给定函数的时间复杂度应该是多少?
- express - 尝试使用 ejs 构建待办事项列表不断收到 TypeError
- sql - 将日期从 UTC 时区转换为 PST 时区(包括 DST 因素)