如何将这部分Python转换为惯用的Javascript
How to translate this bit of Python to idiomatic Javascript
我的代码:
// The q constant of the Glicko system.
var q = Math.log(10) / 400;
function Player(rating, rd) {
this.rating = rating || 1500;
this.rd = rd || 200;
}
Player.prototype.preRatingRD = function(this, t, c) {
// Set default values of t and c
this.t = t || 1;
this.c = c || 63.2;
// Calculate the new rating deviation
this.rd = Math.sqrt(Math.pow(this.rd, 2) + (Math.pow(c, 2) * t));
// Ensure RD doesn't rise above that of an unrated player
this.rd = Math.min(this.rd, 350);
// Ensure RD doesn't drop too low so that rating can still change
// appreciably
this.rd = Math.max(this.rd, 30);
};
Player.prototype.g = function(this, rd) {
return 1 / Math.sqrt(1 + 3 * Math.pow(q, 2) * Math.pow(rd, 2) / Math.pow(Math.PI, 2));
};
Player.prototype.e = function(this, p2rating, p2rd) {
return 1 / (1 + Math.pow(10, (-1 * this.g(p2rd) * (this.rating - p2rating) / 400)));
};
我正在做一个Glicko评级系统的JS/HTML实现,我大量借鉴了pyglicko——也就是说,完全抄袭了它。
这是相当短的(可能少于100 LoC没有评论),但我有我的疑虑,我的翻译是否会工作,因为老实说,我不知道Javascript范围和this
实际上是如何工作的。你可以看到我在顶部的链接。
但具体来说,我想知道你将如何在Javascript中表达这一点Python代码。基本上,_d2
在Player
的类定义中。
def _d2(self, rating_list, RD_list):
tempSum = 0
for i in range(len(rating_list)):
tempE = self._E(rating_list[i], RD_list[i])
tempSum += math.pow(self._g(RD_list[1]), 2) * tempE * (1 - tempE)
return 1 / (math.pow(self._q, 2) * tempSum)
我已经得到了函数e
和g
这样定义,q
是一个常数:
Player.prototype.e = function(this, ratingList, rdList) {
// Stuff goes here
}
在Javascript中,你不需要显式地传递self(实际上,Python在这里是"奇怪的")
Player.prototype.e = function(rating_list, RD_list){
//replace "self" with "this" here:
var tempSum = 0; //if you don't use the "var", tempSum will be a global
// instead of a local
for(var i=0; i<rating_list.length; i++){ //plain old for loop - no foreach in JS
var tempE = this._E( ... ); //note that in JS, just like in Python,
//variables like this have function scope and
//can be accessed outside the loop as well
tempSum += Math.pow( ... ) //the Math namespace is always available
//Javascript doesn't have a native module system
}
return (...);
}
应该可以正常工作。关于this
,你需要知道的唯一棘手的事情是它是非常混杂的。这意味着它是由如何调用函数决定的:
obj.e(); //if you do a method-like call, the this will be set to obj
然而,在幕后并没有魔法绑定。下面的代码可以在python中使用,但是不能在Javascript中使用:
f = obj.e
f(); //looks like a normal function call. This doesn't point to obj
相关文章:
- 将这些正则表达式从javascript转换为Java
- 使用JAVASCRIPT转换货币.可以't通过我的函数设置转换后的输入文本字段的值
- 使用ScriptObjectMirror将数组结果从JavaScript转换为有用的东西
- 如何在javascript转换编码中将一个动态值从一个表单添加到另一个页面
- 使用document.cookie将客户端javascript转换为节点模块
- 将纯javascript转换为jquery
- 按钮标签,javascript 转换为链接标签
- Javascript转换数组
- 如何将此JavaScript转换为插件
- 将可迭代的 Javascript 转换为数组
- DOM元素上的Javascript转换
- 用javascript转换日期
- 将代码从JavaScript转换为PHP
- 将var javascript转换为java变量
- 如何使用javascript转换特殊字符及其实体名称(如&with&)
- 如何将这个javascript转换为jquery
- Clojure到JavaScript转换器(Leiningen)
- .Net Ticks 使用 JavaScript 转换为 ISO 8601 日期格式
- JavaScript 转换用户输入
- 将 Javascript 转换为 coffeescript