本文介绍了在JavaScript中生成字符串中的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想制作一个客户端A / B测试库。
I'd like to make a client-side A/B testing library.
每个用户都有一个存储在cookie中的随机数。每个测试都有一个测试名称和一组选项。我需要一个函数,根据用户的随机数,测试名称和选项选择一个随机选项。当然,对于给定的输入集,函数必须始终返回相同的选项。
Each user has a random number stored in a cookie. Each test has a test name and an array of options. I need a function that picks a random option given the user's random number, the test name, and the options. Of course, the function must always return the same option for a given set of inputs.
如何在JavaScript中编写此函数?
How can I write this function in JavaScript?
推荐答案我目前的解决方案使用 CryptoJS库的MD5 散列函数生成一个随机数:
My current solution uses the CryptoJS library's MD5 hashing function to generate a random number:
// seed is the user's random number choose_option = function(seed, test_name, options) { word = CryptoJS.MD5("" + seed + test_name).words[0]; // take first 32-bit word i = Math.abs(word % options.length); return options[i]; }更多推荐
在JavaScript中生成字符串中的随机数
发布评论