简体   繁体   English

谁能帮我把它变成 js 语法?

[英]can anyone help me to turn this to js syntax?

this is my code that I need to convert from Python to JS, I tried a lot of ways I found online but can't seem to find a working one.这是我需要从 Python 转换为 JS 的代码,我尝试了很多我在网上找到的方法,但似乎找不到有效的方法。 the code works in Python but not in JS, the probability to get ['1','1','1'] is 0.2 and so on.该代码在 Python 中有效,但在 JS 中无效,得到 ['1','1','1'] 的概率为 0.2,依此类推。 thanks!谢谢!

options = [["1","1","1"],["39","39","39"],["10","10","10"],["19","19","19"],["1","1","1"],"2", "lose"]
result = random.choices(options, weights = [0.2,0.8,1,1,2,75,20])[0] 

This should do the trick.这应该可以解决问题。

 var random = { int (min, max) { return Math.floor(Math.random() * (max - min) ) + min; }, choices (options, weights) { // find the total weight. Can also be done by looping let totalWeight = weights.reduce((a, b) => a + b); // getting a random number from 0 till totalWeight let randomNumber = this.int(0, totalWeight); // resetting the totalWeight totalWeight = 0; for (let i in options) { totalWeight += weights[i]; // once the weight hits the randomNumber, return the element if (totalWeight >= randomNumber) { return options[i]; } } // otherwise, return the last element return options[options.length - 1][0]; } } var options = [["1","1","1"],["39","39","39"],["10","10","10"],["19","19","19"],["1","1","1"],"2", "lose"]; var result = random.choices(options, [0.2,0.8,1,1,2,75,20]) console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM