


Detailed example of how to use JavaScript to randomize the value index in an array and create a random array
The example of this article describes the method of javascript to randomize the value index in the array and create a random array. Share it with everyone for your reference. The details are as follows:
Today in the QW communication group, I saw some students discussing the issue of randomizing arrays. The algorithm given was very good, and it reminded me of the not so "beautiful" one I had implemented before. method. Think about it, sometimes when we are busy writing business code just to implement its function, we don't spend much thought on whether there is a better implementation method.
Regarding this array problem (then sort the values in an array and return a new array), my previous implementation method was like this:
function randArr(arr) { var ret = [], obj = {}, i = arr.length, l = i, n; while (--i >= 0) { n = Math.floor( Math.random() * l ); if (obj[n] === void 0) { ret[ret.length] = obj[n] = arr[n]; } else { i++; } } return ret; }
The above code will work, but It is not a good algorithm. It intends to execute the "length of the original array" loop. Each loop will randomly pick an index in the original array, and then determine whether the index has been taken. If not, the value of the index will be Put it into a new array, and if it has been retrieved, increase the decrement key i by 1 (the purpose is to repeat the cycle until another index that has not been retrieved is retrieved). The performance of this method depends on your character. I believe that students who have seen this idea will understand the reason.
Now give the algorithm of the classmate in the group:
function randArr(arr) { var ret = [], i = arr.length, n; arr = arr.slice(0); while (--i >= 0) { n = Math.floor( Math.random() * i); ret[ret.length] = arr.splice(n, 1)[0]; } return ret; }
This is a quite clever algorithm. After taking a random index in each loop, and changing its value from Delete from the array, so that if this index is still randomly fetched later, this index will no longer be the value fetched last time, and the value range of the random number will decrease according to the length of the array, so You can cycle a certain number of times at one time and get the desired result.
I also saw an improved version, which took into account some performance problems caused by the deletion operation of the array and used JK's large shuffling algorithm, that is, changing each deletion operation to a position replacement operation ( The value of the index obtained is exchanged with the value corresponding to the current decrementing key i), so that the impact on the entire array is minimal. Let’s put the code:
function randArr(arr) { var ret = [], i = arr.length, n; arr = arr.slice(0); while (--i >= 0) { n = Math.floor( Math.random() * i); ret[ret.length] = arr[n]; arr[n] = arr[i]; } return ret; }
Finally give a "create value" is a random array between min~max" method, the algorithm principle is similar to the above:
function makeRandArr(min, max) { var ret = [], obj = {}, n; for (; max >= min; max--) { n = Math.ceil( Math.random() * (max - min) ) + min; ret[ret.length] = obj[n] || n; obj[n] = obj[max] || max; } return ret; }
The above is the detailed content of Detailed example of how to use JavaScript to randomize the value index in an array and create a random array. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools
