我有一个对象“区域”(将是世界上的不同区域),并且我将拥有一个包含我应用的各种属性的数组。
我希望对象列表包含执行各种操作的代码,例如标准化内部数据和添加权重。
这里我有 TTT(总行程时间)、TJL(总行程长度)和 PeaceIndex(某处有多危险)作为属性。
一旦我有了整个列表,我就会首先对它们进行标准化排名。
function region(TTT, TJL, peaceIndex) {
var n = function (TTTtopvalue,TTTbottomvalue,TTT) {
var colVal = parseFloat(TTT);
var numerator = colVal - TTTbottomvalue; //Once you have the extremes 33, 55, 56, 77 e.g. 33 and 77 then (value-min)/(max-min) 55-33=22/77-33= 22/50 = .4 whatever
var denominator = TTTtopvalue - TTTbottomvalue;
var result = numerator/denominator
this.TTTnormal =result ;
}
this.TTT = TTT;
this.TJL = TJL;
this.TTTnormal = 0;
this.TTTtopvalue = 0;
this.TTTbottomvalue = 0;
this.peaceIndex = peaceIndex;
this.normaliseTTT = n;
}
var r1 = new region(45, 33, 50);
var r2 = new region(40, 30, 55);
var r3 = new region(333, 100, 1);
var testArray = [r1, r2, r3];
console.log(JSON.stringify(testArray));
testArray[0].TTTtopvalue = 333;
testArray[0].TTTbottomvalue = 40;
testArray[0].normaliseTTT(333,40,45); //this works for TTT!!
console.log(JSON.stringify(testArray));
testArray.sort(function(a, b){
return a.TTT-b.TTT
})
console.log(JSON.stringify(testArray));
现在这对于 TTT 专栏非常有效。然而,TJL 和peaceIndex 列的代码相同。
我似乎无法让匿名函数将标准化值返回给其他属性。
我该怎么做?
所以原型(prototype)是
function (topvalue,bottomvalue,TTT or TJL or peaceIndex)
保存每次输入的内容
最佳答案
关注点分离就是答案。您需要一个单独的类来表示标准化值。
function NormalizedValue(value, top, bottom) {
this.init(value, top, bottom);
}
NormalizedValue.prototype.init = function (value, top, bottom) {
value = parseFloat(value);
top = parseFloat(top);
bottom = parseFloat(bottom);
this.value = value;
this.normalized = (value - bottom) / (top - bottom);
}
然后
function Region(name) {
this.name = name;
this.TTT = new NormalizedValue();
this.TJL = new NormalizedValue();
this.peaceIndex = new NormalizedValue();
}
var r1 = new Region("A");
var r2 = new Region("B");
var r3 = new Region("C");
r1.TTT.init(333, 40, 45);
r1.TJL.init(40, 30, 25);
r1.peaceIndex.init(1, 5, 1);
// and so on for the others...
然后,例如
testArray.sort(function (a, b) {
return a.TTT.normalized - b.TTT.normalized;
});
您可以以不同的方式构造您的 Region
构造函数,以便更多的初始化值可以作为参数传递,但请注意它不会变得太困惑(10 个参数的构造函数不是一个漂亮的东西)。
关于javascript - 在对象中使用匿名函数执行多个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29183885/