10-Number _javascript techniques for JavaScript random extraction of 0-100 without repetition

Source: Internet
Author: User
Tags array length repetition


At present, only learn two simple methods to help you achieve a random 0-100 between the 10 number of repeat, the specific contents are as follows



First Kind the feature that can be rewritten by using array length



Train of thought: You can use a for loop from 0 to 100 to put in an array, and then the 100 numbers are randomly disturbed by using sort (), and then by rewriting the length of the array to 10, you get 10 different numbers.


<! DOCTYPE html>
<html lang = "en">
<head>
   <meta charset = "UTF-8">
   <title> Document </ title>
   <script>
   var arr = [];
   for (var i = 0; i <100; i ++) {// An array from 0 to 100
     arr.push (i);
   }
   arr.sort (function () {// Randomly shuffle this array
     return Math.random ()-0.5;
   })
   arr.length = 10; // Rewrite length
   console.log (arr); // The console will output 10 different numbers
   </ script>
</ head>
<body>
</ body>
</ html>


Second Kind utilizes the unique feature of the key value of the JSON object.



idea: first define an empty array and an empty JSON object,


<! DOCTYPE html>
<html lang = "en">
<head>
   <meta charset = "UTF-8">
   <title> Document </ title>
   <script>
   // json object, the key value is unique, and the key value can be a number
   var arr = [];
   var json = ();
   while (arr.length <10) {
     var k = Math.round (Math.random () * 100);
     if (! json [k]) {
       json [k] = true;
       arr.push (k);
     }
   }
   console.log (arr)
   </ script>
</ head>
<body>
  
</ body>
</ html> 


I hope this article will help you learn the JavaScript programming.


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.