<p>我以前把代码从一种语言转换成另一种语言。你应该避免逐字翻译,而是试着理解代码的作用并翻译它。区分什么是逻辑,什么是该语言的特性或实现细节</p>
<p>尽管markmeyer给了你一个答案,可以将这些行逐字翻译成JS,而且它是有效的,但我建议不要使用这些代码。这在JS中是复杂而缓慢的</p>
<p>因为,与理解这些理解的Python不同,JS还不够聪明,无法理解<code>stat_keys</code>是一个静态的属性名列表,无法优化这些Aray#map调用,然后进行数组分解</p>
<p>我就是这样翻译你的函数的:</p>
<pre><code>// Compute the WN8 of a player.
// why is this function async in your code?
function compute_wn8(stats_totals, exp_stat_totals) {
if (!stats_totals || !exp_stat_totals) {
return 0;
}
const r_dmg = exp_stat_totals.dmgs > 0 ? stats_totals.dmgs / exp_stat_totals.dmgs : 0;
const r_spot = exp_stat_totals.spots > 0 ? stats_totals.spots / exp_stat_totals.spots : 0;
const r_kill = exp_stat_totals.kills > 0 ? stats_totals.kills / exp_stat_totals.kills : 0;
const r_def = exp_stat_totals.defs > 0 ? stats_totals.defs / exp_stat_totals.defs : 0;
const r_win = exp_stat_totals.wins > 0 ? stats_totals.wins / exp_stat_totals.wins : 0;
const r_dmg_c = Math.max(0, (r_dmg - 0.22) / 0.78);
const r_spot_c = Math.max(0, Math.min(r_dmg_c + 0.1, (r_spot - 0.38) / 0.62));
const r_kill_c = Math.max(0, Math.min(r_dmg_c + 0.2, (r_kill - 0.12) / 0.88));
const r_def_c = Math.max(0, Math.min(r_dmg_c + 0.1, (r_def - 0.10) / 0.90));
const r_win_c = Math.max(0, (r_win - 0.71) / 0.29);
return 980 * r_dmg_c
+ 210 * r_dmg_c * r_kill_c
+ 155 * r_spot_c * r_kill_c
+ 75 * r_def_c * r_kill_c
+ 145 * Math.min(1.8, r_win_c);
}
</code></pre>
<p>除此之外,即使在python中,我也不确定</p>
<pre><code>stat_keys = ('dmgs', 'spots', 'kills', 'defs', 'wins')
dmgs, spots, kills, defs, wins = (stats_totals[stat] for stat in stat_keys)
exp_dmgs, exp_spots, exp_kills, exp_defs, exp_wins = (exp_stat_totals[stat] for stat in stat_keys)
r_dmg = dmgs / exp_dmgs if exp_dmgs > 0 else 0
r_spot = spots / exp_spots if exp_spots > 0 else 0
r_kill = kills / exp_kills if exp_kills > 0 else 0
r_def = defs / exp_defs if exp_defs > 0 else 0
r_win = wins / exp_wins if exp_wins > 0 else 0
</code></pre>
<p>比这更好吗</p>
<pre><code>r_dmg = stats_totals.dmgs / exp_stat_totals.dmgs if exp_stat_totals.dmgs > 0 else 0
r_spot = stats_totals.spots / exp_stat_totals.spots if exp_stat_totals.spots > 0 else 0
r_kill = stats_totals.kills / exp_stat_totals.kills if exp_stat_totals.kills > 0 else 0
r_def = stats_totals.defs / exp_stat_totals.defs if exp_stat_totals.defs > 0 else 0
r_win = stats_totals.wins / exp_stat_totals.wins if exp_stat_totals.wins > 0 else 0
</code></pre>
<p>请声明变量并在JS中使用<code>;</code>。你未来的自己会感谢你的</p>