这个函数有效,但是如何避免为第二个变量键入相同的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>
答案 0 :(得分:1)
试试这个。
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;
};
});
答案 1 :(得分:0)
你可以试试这个:
var app=angular.module('xpCalc', []);
app.controller('xpCalculatorController', function($scope){
$scope.currentLevel=1;
var getResult = function(level)
{
var output=0;
for (var thisLVL=1; thisLVL < level; thisLVL++) {
output += (Math.floor(thisLVL+300*Math.pow(2,thisLVL/7))/4);
}
return output;
}
$scope.currentXp=getResult($scope.currentLevel);
$scope.desiredLevel=1;
$scope.desiredXp=getResult($scope.desiredLevel);
});
答案 2 :(得分:0)
任务:
xp = sum[floor(i + 300*2^(i/7)) / 4], i = 1..level
4*xp = sum[i] + sum[floor(300*2^(i/7))], i = 1..level
4*xp = level*(level+1)/2 + sum[floor(300*2^(i/7))], i = [1..level)
我们来到下一个功能:
function getXP(level) {
var xp = level*(level+1)/2, i;
var sum = 0;
for (i = 1; i < level; i++)
sum+=Math.floor(300 * Math.pow(2, i/7));
return (xp + sum) / 4;
}
然而,getXP(5) - getXP(3)
将等于我们跳过前3个步骤
function getXP(to, from) {
from = from || 1;
var xp = 0, i;
for (i = from; i < level; i++)
sum += i + Math.floor(300 * Math.pow(2, i/7));
return xp / 4;
}
因此,您现在可以像{{getXP(desiredLevel, currentLevel)}}
此函数将被称为每个摘要迭代。这很糟糕。
您至少有两种方法可以解决它:
watch
计算重新计算它的参数。 这样的事情:
var hash = {};
function mgetXP(to, from) {
if (typeof hash[key(to, from)] != 'undefined') return hash[key(to, from)];
return hash[key(to, from)] = getXP(to, from);
function key(to, from) {return [to, from].join('_'); }
}
答案 3 :(得分:0)
您也可以尝试这种方法:
$scope.currentLevel=1;
$scope.currentXp = xp($scope.currentLevel);
$scope.desiredLevel=1;
$scope.desiredXp = xp($scope.desiredLevel);
function xp(level) {
function calc(index, result){
if (index >= level) return result;
result += (Math.floor( index + 300 * Math.pow( 2, index / 7 ) ) / 4);
return calc(index + 1, result);
}
return calc(1, 0);
}