Javascript: getting random numbers with four digits or letters _ javascript skills

Source: Internet
Author: User
This article describes how to use javascript to obtain random numbers of four digits or letters. For more information, see the following section.
A simple method is to randomly extract four non-repeating characters from numbers and letters.

The code example is as follows:

Function only (ele, arr) {if (arr. length = 0) {return true ;}for (var j = 0; j

The above Code meets our requirements. The following describes the implementation process of the above Code.


I. Code comments:
1. function only (ele, arr) {}, this function can be used to determine whether the specified index has been used, and random numbers are placed repeatedly.
2. if (arr. length = 0) {}, if the array is empty, it indicates that it cannot be repeated. true is returned.
3. for (var j = 0; j5. (function () {}) (arr), an self-executed function, and passing a parameter.
6. var randNum = null: declare a variable and assign the initial value to null to store randomly generated array indexes.
7. var old = [], create an empty array to store the existing array index values.
8. var str = "", creates an empty string to store the generated random number.
9. function done () {}, which can be used to obtain a random number.
10. randNum = Math. floor (Math. random () * 14) to obtain the index value of the array.
11. if (only (randNum, old )){
Str = str + arr [randNum];
Old. push (randNum );
} To determine whether it has been used. If not, obtain the array element, append it to the str string, and append the index value to the old array.
12. else {done ();
}, If you have already used it, obtain it again. Here we use recursion.
13. for (var index = 0; index <4; index ++ ){
Done ();
}, Use the for loop to obtain four random numbers.

From: http://www.softwhy.com/forum.php? Mod = viewthread & tid = 16493.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.