How to generate a random number in javascript. Generating random integers in JavaScript within a specific range? Round to the nearest number


Technically, the term "random number generator" is nonsense, since numbers themselves are not random. For example, is 100 a random number? What about 25? What this term actually means is that it creates a sequence of numbers that appear randomly. This raises a more difficult question: what is a sequence of random numbers? The only correct answer: a sequence of random numbers is a sequence in which all elements are unrelated. This definition leads to the paradox that any sequence can be either random or non-random, depending on how the sequence is obtained. For example, the following string of numbers
1 2 3 4 5 6 7 8 9 0
was obtained by typing the top line of the keyboard in order, so the sequence cannot be considered randomly generated. But what if you get the same sequence when you take the numbered tennis balls out of the barrel. In this case, it is already a randomly generated sequence. This example shows that the randomness of a sequence depends on how it was obtained, and not on the sequence itself.

Remember that a computer-generated sequence of numbers is deterministic: each number except the first one depends on the numbers before it. Technically, this means that only a quasi-random sequence of numbers can be generated by a computer, i.e. in fact they are not truly random. However, this is sufficient for most tasks and for simplicity such sequences will be called random. One very interesting method was developed by John von Neumann; it is often called root mean square. In this method, the previous random number is squared, and then the middle digits are extracted from the result. For example, if you are creating numbers with three digits, and the previous number was 121, then squaring it gives the result 14641. Isolating the middle three digits gives the next random number 464. The disadvantage of this method is that it has a very short repetition period, called a cycle . For this reason, this method is not used today. Modern methods of generating random numbers are much more complex.

Random numbers in PHP

PHP has two groups of functions for working with random numbers. Purely externally, they can be distinguished by the mt_ prefix for all functions of one of the groups.

Deprecated features
rand function Returns an integer between zero and the value of RAND_MAX (which is 32767). Can have two optional integer parameters - if they are specified, a random number is generated from the first parameter to the second.

Echo rand(); echo rand(1,100); // Give out a random number from 1 to 100

Function srand. Specifies the sequence of random numbers produced by the rand function. It has an entire parameter - for different values ​​of this parameter, rand will produce different sequences of numbers. The srand function only needs to be called once before all calls to the rand function. Usage example:

Srand(1288); // Initialize the random number generator for($i=0; $i 0.0200000000000000004 0.3 - 0.1 > 0.19999999999999998
For practical purposes, this inaccuracy does not matter, in our case we are talking about an error in quintillion parts, however, this may disappoint some. We can also get somewhat strange results when working with numbers that represent currencies, percentages, or file sizes. In order to correct these inaccuracies, we just need to be able to round the results, and it is enough to set the decimal precision.

Rounding numbers has practical applications, we can manipulate a number within a certain range, for example we want to round a value to the nearest whole number rather than working only with the decimal part.

Rounding Decimals To trim a decimal, use toFixed or the toPrecision method. Both of them take a single argument that specifies, respectively, how many significant figures (that is, the total number of digits used in the number) or decimal places (the number after the decimal point) the result should include:
  • If an argument is not defined for toFixed(), it will default to zero, which means 0 decimal places, the argument has a maximum value of 20.
  • If no argument is given to toPrecision, the number is left untouched
  • let randNum = 6.25; randNum.toFixed(); > "6" Math.PI.toPrecision(1); > "3" randNum = 87.335; randNum.toFixed(2); > "87.33" randNum = 87.337; randNum.toPrecision(3); > "87.3"
    Both the toFixed() and toPrecision() methods return a string representation of the result, not a number. This means that when summing a rounded value with randNum, it will produce a concatenation of strings rather than a sum of numbers:

    Let randNum = 6.25; let rounded = randNum.toFixed(); // "6" console.log(randNum + rounded); > "6.256"
    If you want the result to be a numeric data type, then you will need to use parseFloat:

    Let randNum = 6.25; let rounded = parseFloat(randNum.toFixed(1)); console.log(rounded); > 6.3
    Please note that values ​​of 5 are rounded except in rare cases.

    The toFixed() and toPrecision() methods are useful because they can not only cut off the fractional part, but also add decimal places, which is convenient when working with currency:

    Let wholeNum = 1 let dollarsCents = wholeNum.toFixed(2); console.log(dollarsCents); > "1.00"
    Note that toPrecision will produce the result in scientific notation if the number of integers is greater than the precision itself:

    Let num = 123.435 num.toPrecision(2); > "1.2e+2"

    How to Avoid Rounding Errors with Decimals In some cases, toFixed and toPrecision round the value 5 down and up:

    Let numTest = 1.005; numTest.toFixed(2); > "1.00"
    The result of the calculation above should have been 1.01, not 1. If you want to avoid a similar error, we can use the solution proposed by Jack L Moore, which uses exponential numbers for the calculation:

    Function round(value, decimals) ( return Number(Math.round(value+"e"+decimals)+"e-"+decimals); )
    Now:

    Round(1.005,2); > 1.01
    If you want a more robust solution than the one shown above, you can go to MDN.

    Machine epsilon rounding An alternative method for rounding decimal numbers was introduced in ES6. Machine epsilon rounding provides a reasonable margin of error when comparing two floating point numbers. Without rounding, comparisons may produce results similar to the following:

    0.1 + 0.2 === 0.3 > false
    We use Math.EPSILON in our function to get a valid comparison:

    Function epsEqu(x, y) ( return Math.abs(x - y)< Number.EPSILON * Math.max(Math.abs(x), Math.abs(y)); }
    The function takes two arguments: the first is the current calculation, the second is the expected result. It returns a comparison of the two:

    EpsEqu(0.1 + 0.2, 0.3) > true
    All modern browsers already support ES6 math functions, but if you want support in browsers like IE 11, use polyfills.

    Cutting off the fractional part All the methods presented above can round to decimal numbers. In order to simply cut a number to two decimal places, you must first multiply it by 100, and then divide the resulting result by 100:

    Function truncated(num) ( return Math.trunc(num * 100) / 100; ) truncated(3.1416) > 3.14
    If you want to adapt the method to any number of decimal places, you can use bitwise double negation:

    Function truncated(num, decimalPlaces) ( let numPowerConverter = Math.pow(10, decimalPlaces); return ~~(num * numPowerConverter)/numPowerConverter; )
    Now:

    Let randInt = 35.874993; truncated(randInt,3); > 35.874

    Rounding to the Nearest Number To round a decimal number to the nearest number up or down, whichever we're closest to, use Math.round():

    Math.round(4.3) > 4 Math.round(4.5) > 5
    Please note that “half the value”, 0.5 is rounded up according to the rules of mathematics.

    Rounding down to the nearest whole number If you want to always round down, use Math.floor:

    Math.floor(42.23); > 42 Math.floor(36.93); > 36
    Please note that rounding down works for all numbers, including negative numbers. Imagine a skyscraper with an infinite number of floors, including floors on the bottom level (representing negative numbers). If you are in an elevator on the lowest level between 2 and 3 (which represents a value of -2.5), Math.floor will take you to -3:

    Math.floor(-2.5); > -3
    But if you want to avoid this situation, use Math.trunc, supported in all modern browsers (except IE/Edge):

    Math.trunc(-41.43); > -41
    On MDN you will find a polyfill that will provide support for Math.trunc in browsers and IE/Edge.

    Rounding up to the nearest whole number On the other hand, if you always need to round up, use Math.ceil. Again, remember the infinite elevator: Math.ceil will always go "up", regardless of whether the number is negative or not:

    Math.ceil(42.23); > 43 Math.ceil(36.93); > 37 Math.ceil(-36.93); > -36

    Rounding up/down to the number needed If we want to round to the nearest multiple of 5, the easiest way is to create a function that divides the number by 5, rounds it, and then multiplies it by the same amount:

    Function roundTo5(num) ( return Math.round(num/5)*5; )
    Now:

    RoundTo5(11); > 10
    If you want to round to multiples of your value, we use a more general function, passing in the initial value and the multiple:

    Function roundToMultiple(num, multiple) ( return Math.round(num/multiple)*multiple; )
    Now:

    Let initialNumber = 11; let multiple = 10; roundToMultiple(initialNumber, multiple); > 10;

    Fixing a Number in a Range There are many cases where we want to get a value of x that lies within a range. For example, we might need a value between 1 and 100, but we ended up with a value of 123. To fix this, we can use min (returns the smallest of a set of numbers) and max (returns the largest of any set of numbers). In our example, the range is from 1 to 100:

    Let lowBound = 1; let highBound = 100; let numInput = 123; let clamped = Math.max(lowBound, Math.min(numInput, highBound)); console.log(clamped); > 100;
    Again, we can reuse the operation and wrap the whole thing in a function, using the solution proposed by Daniel X. Moore:

    Number.prototype.clamp = function(min, max) ( return Math.min(Math.max(this, min), max); );
    Now:

    NumInput.clamp(lowBound, highBound); > 100;

    Gaussian rounding Gaussian rounding, also known as banker's rounding, involves rounding to the nearest even number. This rounding method works without statistical error. A better solution was suggested by Tim Down:

    Function gaussRound(num, decimalPlaces) ( let d = decimalPlaces || 0, m = Math.pow(10, d), n = +(d ? num * m: num).toFixed(8), i = Math.floor (n), f = n - i, e = 1e-8, r = (f > 0.5 - e && f< 0.5 + e) ? ((i % 2 == 0) ? i: i + 1) : Math.round(n); return d ? r / m: r; }
    Now:

    GaussRound(2.5) > 2 gaussRound(3.5) > 4 gaussRound(2.57,1) > 2.6
    Decimal in CSS:

    Since JavaScript is often used to create positional mappings for HTML elements, you might be wondering what would happen if we generated decimal values ​​for our elements:

    #box ( width: 63.667731993px; )
    The good news is that modern browsers will respect decimal values ​​in the block model, including percentage or pixel units.

    Sorting Very often we need to sort some elements, for example, we have an array of game records, and they must be organized in descending order of player rank. Unfortunately, the standard sort() method has some surprising limitations: it works well with common English words, but immediately breaks down when it encounters numbers, unique characters, or uppercase words. Sorting Alphabetically It would seem that sorting an array alphabetically should be a simple task:

    Let fruit = ["butternut squash", "apricot", "cantaloupe"]; fruit.sort(); > "apricot", "butternut squash", "cantaloupe"]
    However, we run into a problem as soon as one of the elements is uppercase:

    Let fruit = ["butternut squash", "apricot", "Cantalope"]; fruit.sort(); > "Cantaloupe", "apricot", "butternut squash"]
    This is because, by default, the sorter compares the first character represented in Unicode. Unicode is a unique code for any character, regardless of platform, regardless of program, regardless of language. For example, if you look at the code table, the character "a" has the value U+0061 (in hexadecimal 0x61), while the character "C" has the code U+0043 (0x43), which comes earlier in the Unicode table than the character "a".

    To sort an array that may contain mixed case first letters, we need to either convert all elements temporarily to lower case, or define our sort order using the localeCompare() method with some arguments. As a rule, for such a case, it is better to immediately create a function for repeated use:

    Function alphaSort(arr) ( arr.sort(function (a, b) ( return a.localeCompare(b, "en", ("sensitivity": "base")); )); ) let fruit = ["butternut squash ", "apricot", "Cantaloupe"]; alphaSort(fruit) >
    If you want the array sorted in reverse alphabetical order, simply swap the positions of a and b in the function:

    Function alphaSort(arr) ( arr.sort(function (a, b) ( return b.localeCompare(a, "en", ("sensitivity": "base")); )); ) let fruit = ["butternut squash ", "apricot", "Cantaloupe"]; alphaSort(fruit) > ["Cantaloupe", "butternut squash", "apricot"]
    Here it is worth noting that localeCompare is used with arguments, we also need to remember that it is supported by IE11+, for older versions of IE, we can use it without arguments, and in lowercase:

    Function caseSort(arr) ( arr.sort(function (a, b) ( return a.toLowerCase().localeCompare(b.toLowerCase()); )); ) let fruit = ["butternut squash", "apricot", "Cantaloupe"]; caseSort(fruit) > ["apricot", "butternut squash", "Cantaloupe"]

    Numerical sorting All this does not apply to the example we talked about above about the array of game records. With some numeric arrays, sorting works just fine, but at some point the result can be unpredictable:

    Let highScores = ; highScores.sort(); >
    The thing is that the sort() method performs a lexicographic comparison: which means that the numbers will be converted into a string and the comparisons will again be made by matching the first character of that string in the order of the characters in the Unicode table. Therefore, we again need to define our sort order:

    Let highScores = ; highScores.sort(function(a,b) ( return a - b; )); >
    Again, to sort numbers in reverse order, swap the positions of a and b in the function.

    Sorting a JSON-like structure Finally, if we have a JSON-like data structure represented as an array of game records:

    Let scores = [ ( "name": "Daniel", "score": 21768 ), ( "name": "Michael", "score": 33579 ), ( "name": "Alison", "score": 38395 ) ];
    In ES6+, you can use arrow functions:

    Scores.sort((a, b) => b.score - a.score));
    For older browsers that do not have this support:

    Scores.sort(function(a, b) ( return a.score - b.score ));
    As you can see, sorting in JavaScript is a rather obscure thing, I hope that these examples will make life easier somehow.

    Working with Power Functions Exponentiation is an operation originally defined as the result of repeatedly multiplying a natural number by itself; the square root of a is the number that gives a when squared. We could use these functions constantly in everyday life in mathematics lessons, including when calculating areas, volumes, or even in physical modeling.

    In JavaScript, the power function is represented as Math.pow(), and in the new ES7 standard, a new exponentiation operator was introduced - " * * ".

    Raising to a power To raise a number to the nth power, use the Math.pow() function, where the first argument is the number that will be raised to the power, the second argument is the exponent:

    Math.pow(3,2) > 9
    This form of notation means 3 squared, or 3 × 3, which leads to the result 9. Another example can be given, of course:

    Math.pow(5,3); > 125
    That is, 5 cubed, or 5 × 5 × 5, is equal to 125.

    ECMAScript 7 is the next version of JavaScript, in principle, we can use the new proposed exponentiation operator - * *, this form of notation may be more descriptive:

    3 ** 2 > 9
    At the moment, support for this operator is quite limited, so it is not recommended to use it.

    The power function can be useful in a variety of situations. A simple example, calculating the number of seconds in an hour: Math.pow (60,2).

    Square and cube root Math.sqrt() and Math.cbrt() are the opposite of Math.pow(). As we remember, the square root of a is the number that gives a when squared.

    Math.sqrt(9) > 3
    At the same time, the cube root of a is a number that gives a when raised to a cube.

    Math.cbrt(125) > 5
    Math.cbrt() was only recently introduced into the JavaScript specification, and is therefore only supported in modern browsers: Chrome 38+, Firefox and Opera 25+, and Safari 7.1+. You'll notice that Internet Explorer isn't on this list, but you'll find a polyfill on MDN.

    Examples Of course, we can use non-integer values ​​in one of these functions:

    Math.pow(1.25, 2); > 1.5625 Math.cbrt(56.57) > 3.8387991760286138
    Please note that this also works quite well when using negative argument values:

    Math.pow(-5,2) > 25 Math.pow(10,-2) > 0.01
    However, this won't work for square root:

    Math.sqrt(-9) > NaN
    From mathematical analysis we know that an imaginary number refers to the square roots of negative numbers. And this may lead us to another technique for working with complex numbers, but that's another story.

    You can use fractions in Math.pow() to find the square and cube roots of numbers. Square root uses an exponent of 0.5:

    Math.pow(5, 0.5); // = Math.sqrt(5) = 5 ** (1/2) > 2.23606797749979
    However, due to the vagaries of floating point, you can't exactly guess the correct result:

    Math.pow(2.23606797749979,2) > 5.000000000000001
    In such situations, you will have to resort to cutting off signs from the number or rounding to some value.

    Some people, for unknown reasons, in JavaScript confuse the Math.pow() function with Math.exp() , which is the exponential function for numbers in general. Note: In English, "exponent" is translated as "exponent", so this is more likely to apply to English speakers, although there are alternative names for exponent, such as index, power.

    Mathematical Constants Working with math in JavaScript is made easier by a number of built-in constants. These constants are properties of the Math object. It is worth noting that constants are written in uppercase, not CamelCase notation.

    Only registered users can participate in the survey. , Please.

    Tags: Add tags

    There are several examples:

    /** * Returns a random number between min (inclusive) and max (exclusive) */ function getRandomArbitrary(min, max) ( return Math.random() * (max - min) + min; ) /** * Returns a random integer between min (inclusive) and max (inclusive). * The value is no lower than min (or the next integer greater than min * if min isn't an integer) and no greater than max (or the next integer * lower than max if max isn't an integer). * Using Math.round() will give you a non-uniform distribution! */ function getRandomInt(min, max) ( min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; )

    Here's the logic behind it. It's a simple rule of three:

    Math.random() returns a Number between 0 (inclusive) and 1 (exclusive). So we have this interval:

    Num3; num3 = num2 - num3; if (num3< 0) { num3 += 2147483647; } num2 = this.SeedArray; } for (var j = 1; j < 5; j++) { for (var k = 1; k < 56; k++) { this.SeedArray[k] -= this.SeedArray; if (this.SeedArray[k] < 0) { this.SeedArray[k] += 2147483647; } } } this.inext = 0; this.inextp = 21; Seed = 1; } Random.prototype.milliseconds = function () { var str = new Date().valueOf().toString(); return parseInt(str.substr(str.length - 6)); }; Random.prototype.InternalSample = function () { var num = this.inext; var num2 = this.inextp; if (++num >= 56) ( num = 1; ) if (++num2 >= 56) ( num2 = 1; ) var num3 = this.SeedArray - this.SeedArray; if (num3 == 2147483647) ( num3--; ) if (num3< 0) { num3 += 2147483647; } this.SeedArray = num3; this.inext = num; this.inextp = num2; return num3; }; Random.prototype.Sample = function () { return this.InternalSample() * 4.6566128752457969E-10; }; Random.prototype.GetSampleForLargeRange = function () { var num = this.InternalSample(); var flag = this.InternalSample() % 2 == 0; if (flag) { num = -num; } var num2 = num; num2 += 2147483646.0; return num2 / 4294967293.0; }; Random.prototype.Next = function (minValue, maxValue) { if (!minValue && !maxValue) return this.InternalSample(); var num = maxValue - minValue; if (num количество элементов диапазона = 247 - 78 + 1 = 170; (так как обе границы включены.

    /*Mthod 1:*/ var i = 78, j = 247, k = 170, a = , b = , c, d, e, f, l = 0; for(; i 20) ( bool = true; ) else ( bool = false; ) ) return number; )

    Using the following code, you can generate an array of random numbers without repetition within a given range.

    Function genRandomNumber(how_many_number,min,max) ( // parameters // how_many_number: how many numbers you want to generate. For example it is 5. // min(inclusive) : minimum/low value of a range. it must be any positive integer but less than max. i.e 4 // max(inclusive) : maximun value of a range. it must be any positive integer. i.e 50 // return type: array var random_number = ; for (var i = 0; i< how_many_number; i++) { var gen_num = parseInt((Math.random() * (max-min+1)) + min); do { var is_exist = random_number.indexOf(gen_num); if (is_exist >= 0) ( gen_num = parseInt((Math.random() * (max-min+1)) + min); ) else ( random_number.push(gen_num); is_exist = -2; ) ) while (is_exist > -1 ); ) document.getElementById("box").innerHTML = random_number; )

    To get a random number, say between 1 and 6, first do:

    0.5 + (Math.random() * ((6 - 1) + 1))

    This multiplies the random number by 6 and then adds 0.5 to it. Then round the number to a positive integer by doing:

    Math.round(0.5 + (Math.random() * ((6 - 1) + 1))

    This rounds the number to the nearest whole number.

    Or to make it clearer, do this:

    Var value = 0.5 + (Math.random() * ((6 - 1) + 1)) var roll = Math.round(value); return roll;

    In general, the code for this using variables is:

    Var value = (Min - 0.5) + (Math.random() * ((Max - Min) + 1)) var roll = Math.round(value); return roll;

    The reason to subtract 0.5 from the minimum value is that using only the minimum value will allow you to get an integer that would be greater than your maximum value. By removing 0.5 from the minimum value you are essentially preventing the maximum value from being rounded up.

    Hope this helps.

    Random integer between lowest and highest:

    Function randomRange(l,h)( var range = (h-l); var random = Math.floor(Math.random()*range); if (random === 0)(random+=1;) return l+random; )

    Not the most elegant solution.. but something fast.

    Function getRandomInt(lower, upper) ( //to create an even sample distribution return Math.floor(lower + (Math.random() * (upper - lower + 1))); //to produce an uneven sample distribution // return Math.round(lower + (Math.random() * (upper - lower))); //to exclude the max value from the possible values ​​//return Math.floor(lower + (Math.random() * ( upper - lower))); )

    To test this feature and variations of this feature, save the below HTML/JavaScript to a file and open it in a browser. The code will show a graph showing the distribution of one million function calls. The code will also record edge cases, so if the function produces a value greater than max, or less than min, you.will.know.about.it.

    function getRandomInt(lower, upper) ( //to create an even sample distribution return Math.floor(lower + (Math.random() * (upper - lower + 1))); //to produce an uneven sample distribution // return Math.round(lower + (Math.random() * (upper - lower))); //to exclude the max value from the possible values ​​//return Math.floor(lower + (Math.random() * ( upper - lower))); ) var min = -5; var max = 5; var array = new Array(); for(var i = 0; i Number.MAX_SAFE_INTEGER || min< Number.MIN_SAFE_INTEGER) { throw new Error("Arguments must be safe integers."); } else if (range >maxGeneratedValue) ( ​​throw new Error("Range of $(range) (from $(min) to $(max)) > $(maxGeneratedValue)."); ) else if (max< min) { throw new Error("max (${max}) must be >= min ($(min)."); ) else if (min === max) ( return min; ) let generated; do ( generated = crypto.getRandomValues(new Uint32Array(1)); ) while (generated > maxUnbiased); return min + (generated % possibleResultValues); ); console.log(randomInteger(-8, 8)); // -2 console.log(randomInteger(0, 0)); // 0 console.log( randomInteger(0, 0xFFFFFFFF)); // 944450079 console.log(randomInteger(-1, 0xFFFFFFFF)); // Error: Range of 4294967296 covering -1 to 4294967295 is > 4294967295. console.log(new Array(12). fill().map(n => randomInteger(8, 12))); //

    The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) with approximately uniform distribution over that range - which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

    Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the method.

    Syntax Math.random() Return value

    A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).

    Examples

    Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random() itself) aren't exact. If extremely large bounds are chosen (2 53 or higher), it"s possible in extremely rare cases to calculate the usually-excluded upper bound.

    Getting a random number between 0 (inclusive) and 1 (exclusive) function getRandom() ( return Math.random(); ) Getting a random number between two values

    This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min , and is less than (and not equal) max .

    Function getRandomArbitrary(min, max) ( return Math.random() * (max - min) + min; )

    Getting a random integer between two values

    This example returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn't an integer), and is less than (but not equal to) max .

    Function getRandomInt(min, max) ( min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive)

    It might be tempting to use Math.round() to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs.

    Getting a random integer between two values, inclusive

    While the getRandomInt() function above is inclusive at the minimum, it"s exclusive at the maximum. What if you need the results to be inclusive at both the minimum and the maximum? The getRandomIntInclusive() function below accomplishes that.

    Function getRandomIntInclusive(min, max) ( min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; // The maximum is inclusive and the minimum is inclusive)

    Specifications Specification Status Comment
    ECMAScript 1st Edition (ECMA-262) Standard Initial definition. JavaScript 1.0 (UNIX Only) / JavaScript 1.1 (All platforms).
    ECMAScript 5.1 (ECMA-262)
    Standard
    ECMAScript 2015 (6th Edition, ECMA-262)
    The definition of "Math.random" in that specification.
    Standard
    ECMAScript Latest Draft (ECMA-262)
    The definition of "Math.random" in that specification.
    Draft
    Browser compatibility

    The compatibility table in this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

    Update compatibility data on GitHub

    Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.jsrandom
    Chrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes

    An “algorithm” for randomly selecting values ​​from an array without repeating them. More specifically, as part of my JS training, I used it to generate a classic RPG group of characters (barbarian, mage, thief, knight, priest), without repeating classes and names.

    The principle is extremely simple, but it can be useful for JS beginners like me. The connection to RPG is purely symbolic - now I’m actively trying to change my profile from marketing to IT (I realized that my soul lies), and practicing in a game form is much more interesting.

    1. Create a template Before generating a group of characters, you need to set a template for their generation. Actually, here it is:

    Function GamePlayer(n, r, l, p) ( this.nick = n; this.role = r; this.level = l; this.portrait = p; )
    In fact, this function will create characters from the variables through which it will be called. For example:

    Var player1 = new GamePlayer("Power Ranger","barbarian","64","img/barbarian.jpg")
    Now the player1 variable stores a level 64 Power Ranger barbarian with a specific portrait; we can display any of its parameters in the body of the page using player1.nick, player1.level, etc.

    The values ​​(n, r, l, p) from GamePlayer are responsible for receiving and the order in which data is received into the function. If in the example we swap n and r, then the powerful ranger Barbarian will remain in player1, which does not quite correspond to the task.

    2. Define arrays In order not to create characters ourselves, but to almost randomly generate them (as promised in the title), we need arrays from which we will take the parameters of these same characters. As already described above, we have only 4 parameters: character name, class, level and portrait.

    Array for name:

    Var playerNames = ["Rabbit Helpless", "Warm Dreaded Foal", "Desire Kit", "Angel Dusty", "Sweety Frozen", "Silver Heavy Wombat", "Lost Puma", "Vital Panda", "Rolling Sun" , "Steel Runny", "Young Fox", "Needless Ruthless Volunteer", "Chipmunk Cult", "Indigo Puppy"];
    It would be possible to go further and generate names from 2-3 components, but the algorithm for such an improvement does not contain anything new (the same randomness), and then it would simply complicate the learning process.

    Array for class:

    Var playerRoles = ["barbarian", "mage", "rogue", "knight", "priest"];
    Everything is just as obvious. Several strings, from which we will then select values ​​to display on the page.

    Array for level:

    In this particular example, I wanted all party members to be between level 60 and 70. But, since conditions may change, it was necessary to create an array from level 0 to 80, from which then select the required values. Created in a loop:

    Var playerLevels = ; for (i = 0;i





    

    2024 gtavrl.ru.