我有以下js函数:
function Weekday (name, traffic) {
this.name = name;
this.traffic = traffic;
}
function mostDays(){
var traffic=[];
traffic[0] = new Weekday('monday',6);
traffic[1] = new Weekday('tuesday',5);
return traffic;
}
function mostPopularDays(week) {
if(week.length == 0 || week === null) return null;
return Math.max.apply(Math, week['traffic']);
}
所以,如果我说:
var x = mostDays();
var test = mostPopularDays(x);
我正在尝试返回6,这是工作日对象中流量的最大值。有没有办法正确引用它,还是我需要在循环中完成所有这些?
答案 0 :(得分:1)
您可以映射对象的所需属性,然后获取最大值。
function Weekday(name, traffic) {
this.name = name;
this.traffic = traffic;
}
function mostDays() {
var traffic = [];
traffic[0] = new Weekday('monday', 6);
traffic[1] = new Weekday('tuesday', 5);
return traffic;
}
function mostPopularDays(week) {
if (!week.length) return null;
return Math.max.apply(Math, week.map(function (o) { return o.traffic; }));
}
var x = mostDays();
var test = mostPopularDays(x);
console.log(test);
使用ES6,您可以传播Math.max
的值。
function Weekday(name, traffic) {
this.name = name;
this.traffic = traffic;
}
function mostDays() {
return [
new Weekday('monday', 6),
new Weekday('tuesday', 5)
];
}
function mostPopularDays(week) {
if (!week.length) return null;
return Math.max(...week.map(o => o.traffic));
}
var x = mostDays();
var test = mostPopularDays(x);
console.log(test);
答案 1 :(得分:0)
如果您想要返回流量最多的日期,那么Math.max
无法独立完成,因为它只会返回最高流量(如果您正确编码),而不是当天。
您可以使用find
查找流量最高的一天:
var maxTraffic = Math.max(...week.map(day => day.traffic));
return week.find(day => day.traffic === maxTraffic);
答案 2 :(得分:0)
另一个选项可以是指定对象的默认valueOf
:
function Weekday(name, traffic) {
this.name = name;
this.traffic = traffic;
}
Weekday.prototype.valueOf = function() { return this.traffic }
var days = [ new Weekday('monday', 6), new Weekday('tuesday', 5) ]
console.log( Math.max.apply(0, days) )
console.log( Math.max(...days) )
否则,可以使用reduce
:
function Weekday(name, traffic) {
this.name = name;
this.traffic = traffic;
}
var days = [ new Weekday('monday', 6), new Weekday('tuesday', 5) ]
var max = days.reduce((m, d) => Math.max(m, d.traffic), 0)
console.log(max )