Js achieves random acquisition of element _ javascript skills from Arrays

Source: Internet
Author: User
This article mainly introduces how to use js to randomly retrieve elements from arrays and share js code encapsulated by individuals. it is very practical. we recommend this article to our partners:

Copy an array:

(1) cyclic traversal replication (not recommended)

The code is as follows:


Var arry = [1, 5, 9, 7],
New_arry = [],
N = 0,
Len = arry. length;
For (; n New_arry.push (arry [n]);
}

(2) the concat () method is used to connect two or more arrays. this method does not change the existing array, but only returns a copy of the connected array.

The code is as follows:


Var arry = [1, 5, 9, 7],
New_arry = arry. concat ();
Console. log (new_arry );

(3) the slice () method returns the selected element from the existing array.

The code is as follows:


Var arry = [1, 5, 9, 7],
New_arry = arry. slice (0 );
Console. log (new_arry );

Random number:

Math. random ()
Math. random () returns a random number ranging from 0 to 1, for example, 0.4261967441998422.

Personal encapsulation functions:

The code is as follows:


Function getRandom (opt ){
Var old_arry = opt. arry,
Range = opt. range;
// Prevent exceeding the length of the array
Range = range> old_arry.length? Old_arry.length: range;
Var newArray = []. concat (old_arry), // copy the original array without damaging the original array
ValArray = [];
For (var n = 0; n <range; n ++ ){
Var r = Math. floor (Math. random () * (newArray. length ));
ValArray. push (newArray [r]);
// Delete the original array and avoid repeated acquisition in the next loop
NewArray. splice (r, 1 );
}
Return valArray;
}
Var new_val = getRandom ({'arry': [1, 6, 8, 0, 3], 'range': 3 });
Console. log (new_val );

Is it easy to use? it is a very practical code. here we will separate it from my project and share it with you. I hope it will help you.

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.