灵活地使用Math.random [英] Using Math.random flexibly

查看:118
本文介绍了灵活地使用Math.random的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个4个字母的长字符串,RANDOMLY包含字符串中的任何字母:ROYGBV。

I would like to create a 4 letter long string, RANDOMLY containing any of the letters from the string: "ROYGBV".

我所做的就是这个:

function generateSolution(){
    var colors = "ROYGBV";
    var str = "";
    for (var i=0; i<4; i++) {
        var loc = Math.ceil( Math.random()*colors.length );
        str += colors.charAt(loc);
    }

    return str;
}

但这似乎不对,为什么会这样?

But this doesn't seem right, why is this?

此外,这是来自练习的解决方案:

also, this is from the exercise's solution:

str += colors.charAt((Math.random() * 6) | 0);

我在我的解决方案中使用Math.ceil来防止像4.333123这样的随机浮动等等。这个解决方案是如何工作的,而不是舍入randomed数字?

I used Math.ceil in my solution to prevent randoming floats like 4.333123 and so on. How does this solution work, without rounding the randomed numbers?

此外, | 运算符是什么意思?以及第二个解决方案中的随机化如何实际起作用?

Also, what does the | operator mean? and how does the randomization in the second solution actually work?

推荐答案

| 按位OR运算符。由于JavaScript中的按位运算仅适用于32位整数,因此这是将数字舍入为0的简便方法。在您的情况下,它等同于:

The | is the bitwise OR operator. Since bitwise operations in JavaScript only work with 32-bit integers, that's a shorthand way of rounding a a number towards 0. In your case it's equivalent to this:

colors.charAt(Math.floor((Math.random() * 6)));

这个数字需要上下而不是四舍五入,因为你现在正在使用 ceil ,否则您将错过数组的第一个元素(位于索引0处)。

The number needs to be floored instead of rounded up, as you are currently doing with ceil, or you will miss the first element of the array (which is at index 0).

以下是该数据的完整详细信息。从规范转换为整数:

Here's the full details of the conversion to integer from the spec:

生产A:A @ B,其中@是上述产品中的一个按位运算符,其评估如下:

The production A : A @ B, where @ is one of the bitwise operators in the productions above, is evaluated as follows:


  1. lref 成为评估 A 的结果。

  2. lval 是GetValue( lref )。

  3. rref 成为评估 B 的结果。

  4. rval 成为GetValue( rref )。

  5. lnum 是ToInt32( lval )。

  6. rnum 成为ToInt32( rval )。

  7. 返回将按位运算符@应用于lnu的结果m和rnum。结果是带符号的32位整数。

  1. Let lref be the result of evaluating A.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating B.
  4. Let rval be GetValue(rref).
  5. Let lnum be ToInt32(lval).
  6. Let rnum be ToInt32(rval).
  7. Return the result of applying the bitwise operator @ to lnum and rnum. The result is a signed 32 bit integer.


这篇关于灵活地使用Math.random的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆