Hướng dẫn dùng randommath JavaScript

- Ở bài học trước, tôi đã giới thiệu sơ qua về phương thức random() của đối tượng Math, nó dùng để tạo một số ngẫu nhiên trong khoảng từ 0 đến 1 (không bao gồm số 1)

- Tuy nhiên không dừng lại ở đó, nếu phương thức random() được sử dụng kết hợp với các phương thức khác thì nó có thể tạo ra những số ngẫu nhiên đa dạng hơn.

- Ở bài hướng dẫn này, tôi sẽ giới thiệu đến bạn kỹ thuật để tạo một số ngẫu nhiên đa dạng hơn thông qua những ví dụ.

1) Tạo một số nguyên ngẫu nhiên

Tạo một số nguyễn ngẫu nhiên trong đoạn từ 0 đến 9


Xem ví dụ

Tạo một số nguyễn ngẫu nhiên trong đoạn từ 0 đến 10


Xem ví dụ

Tạo một số nguyễn ngẫu nhiên trong đoạn từ 0 đến 99


Xem ví dụ

Tạo một số nguyễn ngẫu nhiên trong đoạn từ 0 đến 100


Xem ví dụ

Tạo một số nguyễn ngẫu nhiên trong đoạn từ 1 đến 10


Xem ví dụ

Tạo một số nguyễn ngẫu nhiên trong đoạn từ 1 đến 100


Xem ví dụ

Tạo một số nguyễn ngẫu nhiên trong đoạn từ 3 đến 7


Xem ví dụ

Tạo một số nguyễn ngẫu nhiên trong đoạn từ 3 đến 9


Xem ví dụ

2) Xây dựng hàm dùng để tạo số nguyên ngẫu nhiên

- Ta thấy trong mỗi ví dụ phía trên, giá trị trả về luôn nằm trong một đoạn nhất định, ví dụ:

  • Từ 0 đến 9
  • Từ 1 đến 100
  • Từ 3 đến 7
  • ....

    ==> Điều đó thật hạn chế nếu như ta muốn tạo nhiều số nguyên trong nhiều đoạn khác nhau.

- Từ đây, để giải quyết vấn đề này thì chúng ta nên xây dựng một hàm tạo số nguyên ngẫu nhiên, chỉ với việc thay đổi giá trị của tham số là ta đã có thể xác định được một đoạn mới.

Tạo một số nguyên ngẫu nhiên trong đoạn từ "min" đến "max" (không bao gồm max)


Xem ví dụ

Tạo một số nguyên ngẫu nhiên trong đoạn từ "min" đến "max" (bao gồm max)


Xem ví dụ

The Math.random() function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 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.

Nội dung chính Show

  • Return value
  • Getting a random number between 0 (inclusive) and 1 (exclusive)
  • Getting a random number between two values
  • Getting a random integer between two values
  • Getting a random integer between two values, inclusive
  • Specifications
  • Browser compatibility
  • Video học lập trình mỗi ngày
  • javascript rand
  • Math.random() function
  • Math.floor() function
  • Math.ceil() function
  • Math.round() function
  • Math.randomInt(min, max) JavaScript
  • Math.randomDec(min, max, decimals)
  • Math.randomList(list)

Try it

Note: 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 window.crypto.getRandomValues() method.

Syntax

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 (253 or higher), it's possible in extremely rare cases to reach 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
}

Note: 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
ECMAScript Language Specification
# sec-math.random

Browser compatibility

BCD tables only load in the browser

See also

Nội dung bài viết

Video học lập trình mỗi ngày

javascript rand

Math.random() JavaScript. Đúng là JavaScript, cái gì cũng có. Hôm qua làm một task dính đến việc random để lấy robo ra tương tác, nên tiện thể ghi lại cho anh em mấy mẹo làm random trong JavaScript. Trong đó sẽ có những method lưu ý sau, Math.random(), Math.floor(), Math.ceil(), Math.round().

Đọc thêm tips javascript

Tipjs - 5 cách chuyển value sang string trong javascript

Math.random() function

Trong JavaScript nếu bạn muốn random giữa 0 và 1 thì sử dụng Math.random() function

console.log(Math.random())
0.5408145050563944

Nếu bạn muốn random giữa 0 và 10 thì chỉ việc nhân thêm 10 như dưới đây.

console.log(Math.random() * 10)

Nhưng số ra không đẹp được chính vì vậy sử dụng thêm Math.floor()

Math.floor() function

Sử dụng Math.floor() để làm tròn số xuống ví dụ:

console.log(Math.floor(5.95));
// expected output: 5

console.log(Math.floor(5.05));
// expected output: 5

Sử dụng Math.floor()Math.random(), random giữa 0 - 10

console.log(Math.floor(Math.random() * 10))

Math.ceil() function

Sử dụng Math.ceil() để làm tròn gần số lên ví dụ:

console.log(Math.ceil(.95));
// expected output: 1

console.log(Math.ceil(4));
// expected output: 4

console.log(Math.ceil(7.004));
// expected output: 8
console.log(Math.ceil(Math.random() * 10))

Math.round() function

Sử dụng Math.round() để làm tròn gần số nào nhất ví dụ:

console.log(Math.round(0.9));
// expected output: 1

console.log(Math.round(5.95), Math.round(5.5), Math.round(5.05));
// expected output: 6 6 5
console.log(Math.round(Math.random() * 10))

Trên đây là những khái niệm basic để làm nền tảng cho việc lập trình, nếu bạn muốn random từ 4 -> 10 thì làm như thế nào? Hoặc random số thập phân từ 4 -> 10 thì làm thế nào? Hoặc bạn muốn random một list thì làm sao? Hãy xem tiếp

Math.randomInt(min, max) JavaScript

Get random một số integer giữa min và max

Math.randomInt = function (min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

Use Math.randomInt()

Click the button!

Math.randomDec(min, max, decimals)

Get random một num có hai số thập phân giữa min và max

Math.randomDec = function (min, max, decimals) {
        return (Math.random() * (max - min) + min).toFixed(decimals || 2);
};

Use Math.randomDec()

Click the button!

Math.randomList(list)

Get random value trong một array

Math.randomList = function (list) {
        return list[Math.randomInt(0, list.length)];
};

Use Math.randomList()

Click the button!

Code Full

(function () {
    Math.randomInt = function (min, max) {
        return Math.floor(Math.random() * (max - min)) + min;
    };
    Math.randomDec = function (min, max, decimals) {
        return (Math.random() * (max - min) + min).toFixed(decimals || 2);
    };
    Math.randomList = function (list) {
        return list[Math.randomInt(0, list.length)];
    };
})();

Đọc thêm tips javascript

Tipjs - 5 cách chuyển value sang string trong javascript