此函数有效,但是如何避免为第二个变量键入相同的for循环,而仅使用一个变量。尝试在这里不重复您自己的方法。我需要使用数组吗?

JS:

var app=angular.module('xpCalc', []);
app.controller('xpCalculatorController', function($scope){
$scope.currentLevel=1;
$scope.currentXp=function(){
    var output=0;
    for (var thisLVL=1; thisLVL < $scope.currentLevel; thisLVL++) {
        output += ( Math.floor ( thisLVL + 300 * Math.pow( 2, thisLVL / 7 ) ) / 4 );
    }
    return output;
  };
  $scope.desiredLevel=1;
  $scope.desiredXp=function(){
    var output=0;
    for (var thisLVL=1; thisLVL < $scope.desiredLevel; thisLVL++) {
        output += ( Math.floor ( thisLVL + 300 * Math.pow( 2, thisLVL / 7 ) ) / 4 );
    }
    return output;
  };
});

HTML:
<h2>{{desiredXp()-currentXp()}}</h2>

最佳答案

试试这个。

var app=angular.module('xpCalc', []);
app.controller('xpCalculatorController', function($scope){
$scope.currentLevel=1;
$scope.currentXp=InternalLoop($scope.currentLevel);
$scope.desiredLevel=1;
$scope.desiredXp=InternalLoop($scope.desiredLevel);

function InternalLoop(level){
    var output=0;
    for (var thisLVL=1; thisLVL < level; thisLVL++) {
        output += ( Math.floor ( thisLVL + 300 * Math.pow( 2, thisLVL / 7 ) ) / 4 );
    }
    return output;
  };

});

07-24 17:44