在JavaScript中生成字符串中的随机数

编程入门 行业动态 更新时间:2024-10-18 18:23:24
本文介绍了在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中生成字符串中的随机数

本文发布于:2023-11-09 20:56:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573411.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   字符串   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!