我遇到了以下问题:函数中的every
方法返回undefined
,因此ableToMoveAll
函数返回无论如何都会下降。请查看下面的代码,并为我提供帮助:
var SQUADS = [];
function MilitaryUnit(name, maxHealth, maxEnergy){
this.squadName = name;
this.squadMaxHealth = maxHealth;
this.squadCurrentHealth = maxHealth;
this.squadMaxEnergy = maxEnergy;
this.squadCurrentEnergy = maxEnergy;
this.travel = function(dist){
if (dist > this.squadCurrentEnergy) {
alert("You can't go this far");
}
this.squadCurrentEnergy -= dist;
}
this.ableToMove = function(dist){
return this.squadCurrentEnergy >= dist;
}
}
var squadOfHorses = new MilitaryUnit("Horses", 50, 100);
SQUADS.push(squadOfHorses);
var squadOfSoldiers = new MilitaryUnit("Soldiers", 40, 50);
SQUADS.push(squadOfSoldiers);
var squadOfMachines = new MilitaryUnit("Machines", 100, 50);
SQUADS.push(squadOfMachines);
Array.prototype.ableToMoveAll = function(dist){
return this.every(function(el){
el.ableToMove(dist)
});
}
先谢谢您
答案 0 :(得分:6)
不是every
方法返回undefined
,而是您传递给它的回调。您忘记了return
语句:
return this.every(function(el){
return el.ableToMove(dist)
// ^^^^^^
});