function getRandomValue(param1, param2) {// 生成一个0到1之间的随机数const randomNum = Math.random();// 定义40%和60%的概率const probability1 = 0.4; // param1的概率为40%const probability2 = 0.6; // param2的概率为60%// 根据概率返回相应的参数if (randomNum < probability1) {return param1;} else {return param2;}
}// 示例调用
const result = getRandomValue('Value1', 'Value2');
console.log(result); // 根据概率打印Value1或者Value2
在这个脚本中:
- getRandomValue函数接受两个参数- param1和- param2。
- Math.random()函数生成一个介于 0 和 1 之间的随机数。
- 如果生成的随机数小于 0.4,返回param1,否则返回param2。这确保了param1被返回的概率是 40%,param2被返回的概率是 60%。
你可以多次运行这个脚本来测试概率分布。