Collection of common js code segments

Source: Internet
Author: User

The front of each code segment has function annotations, parameter requirements, and other explanatory text, so it is not difficult to make more comments. To make it clear, make a small directory in sequence:
Override window. setTimeout,
Understand the return rules of recursive Programs,
Truncate a long string,
Obtain the absolute position of an element on the page,
Counting and removing repeated characters (implemented in multiple methods ),
Random disruption of ordered array elements (implemented in multiple methods ).

Copy codeThe Code is as follows:
/*
Function: Modify window. setTimeout to pass Parameters and object parameters (also available for setInterval)
Usage: setTimeout (callback function, time, parameter 1,..., parameter n) (FF is supported by native, and IE is not supported)
*/
Var _ sto = setTimeout;
Window. setTimeout = function (callback, timeout, param ){
Var args = Array. prototype. slice. call (arguments, 2 );
Var _ cb = function (){
Callback. apply (null, args );
}
_ Sto (_ cb, timeout );
}
Function aaaaa (a, B, c ){
Alert (a + B + c );
}
Window. setTimeout (aaaaa, 5, 6, 7 );

/**//*
Function: Understand the return rules of recursive Programs (from the inside out)
Mutual reference of members between objects
*/
Var ninja = {
Yell: function (n ){
Return n> 0? Ninja. yell (n-1) + "a": "hiy ";
}
};
Alert (ninja. yell (4) // The result is hiyaaaa;
Var samurai = {yell: ninja. yell };
// Var ninja ={}; // whether or not the annotation here affects the result
Try {
Alert (samurai. yell (4 ));
} Catch (e ){
Alert ("Uh, this isn' t good! Where 'd ninja. yell go? ");
}

/** Function: intercept long strings
* @ Param {string} str string to be intercepted
* @ Param {number} size (single-byte length)
*/
Var subStr = function (str, size ){
Var curSize = 0, arr = [];
For (var I = 0, len = str. length; I <len; I ++ ){
Arr. push (str. charAt (I ));
If (str. charCodeAt (I)> 255 ){
CurSize + = 2;
If (size = curSize | size = curSize-1 ){
Return arr. join ('');
}
} Else {
CurSize ++;
If (size = curSize ){
Return arr. join ('');
}
}
}
};
Var str = '# % *...... & # What? 1234 abcd is not long enough ';
Alert (str. length );
Alert (str. substr (0, 15 ));
Alert (subStr (str, 15 ));

/**//*
Function: Obtain the absolute position of an element on the page (relative to the upper left corner of the page)
@ Param {string} the DOM element of the node to be located
*/
Function getAbsPosition (node ){
Var t = node. offsetTop;
Var l = node. offsetLeft;
While (node = node. offsetParent ){
T + = node. offsetTop;
L + = node. offsetLeft;
}
Alert ("top =" + t + "\ n" + "left =" + l );
}

/**//*
Function: Count and remove duplicate characters
@ Param str: string to be counted
Note: It is often used to count the number of repeated characters in a string or repeated letters and numbers in an array.
Here we collect two typical types from the Internet. There are two implementation methods respectively. There are many other variants, which can be searched and learned from different perspectives.
The data to be counted, whether it is an Array or a String, can be used only with String. split () or Array. join ()
Convert to the type required by function parameters.
*/
// Type 1: Use a new object to save data
Var count1 = function (str ){
Var map ={}, maxCount = 0, maxChar, undefined, I = str. length;
While (I --){
Var t = str. charAt (I );
Map [t] = undefined? Map [t] = 1: map [t] + = 1;
If (map [t]> maxCount ){
MaxChar = t;
MaxCount = map [maxChar];
}
}
Return "character:" + maxChar + "Times:" + maxCount;
}
Function s_0 (a) {// The parameter here should be of the array type
Var B = {}, c = [], I;
For (I = 0; I <a. length; I ++ ){
If (! B [a [I]) {
C [c. length] = a [I], B [a [I] = true;
}
}
Return c;
}
// Type 2: Regular Expression matching statistics
Var count2 = function (str ){
Var most = str. split (''). sort (). join (''). match (/(.) \ 1 */g); // sort repeated characters
Most = most. sort (function (a, B) {return a. length-B. length}). pop (); // sort by occurrence frequency
Return most. length + ':' + most [0];
}
Function s_1 (){
Var a = a. join (""), B = [];
While (a. length> 0)
A = a. replace (new RegExp (B [B. length] = a. charAt (0), "g "),"");
Return B;
}

/**//*
Function: disrupt ordered arrays (generate unordered Random Arrays)
Note: The basic sorting algorithms should be clear to everyone. However, the opposite operation is often used in programming, that is, to randomly disrupt the original ordered array elements.
The following three methods are provided. The first method is the one I wrote before. Due to the poor level, the time required to write the code is too complex,
Therefore, you can search for some simple and efficient methods on the Internet.
The second is said to be the shuffling algorithm, which many people may have heard;
The third method is to use JS's built-in sort method, which is easy to implement.
*/
// Method 1 (lessons learned from failure)
Function randArray (num ){
Var rands = [];
Var ra = parseInt (num * Math. random ());
Rands. push (ra );
For (var r = 0; r <num-1; r ++ ){
Ra = parseInt (num * Math. random ());
For (var m = 0; m <rands. length; m ++ ){
While (rands [m] = ra ){
Ra = parseInt (num * Math. random ());
M =-1;
}
}
Rands. push (ra );
}
// Alert (rands );
Return rands;
}
// Method 2:
// Select a random number between two [0... array. Length) and change them as the positions of the two elements under the target (this is efficient in disordered order)
/* Note: This is a shuffling algorithm. Someone has demonstrated the following effect:
The random exchange nums/2 times results in poor performance. On average, about 1/3 of the objects are still in the original position.
The random exchange nums is basically available, and about 15% of the objects are still in the original position on average.
Random exchange nums * is available twice, and an average of about 2% of objects are still in the original position.
*/
Function daluan (nums ){
Var array = [];
For (var I = 0; I <nums; I ++ ){
Array [I] = I;
}
For (var I = 0; I <nums; I ++ ){
Var rand = parseInt (nums * Math. random ());
Var temp = array [I];
Array [I] = array [rand];
Array [rand] = temp;
}
Return array;
}
// Method 3:
// Let the comparison function return-1 or 1 at random (so the efficiency of disordered sorting may not be high)
Var testArray3 = [,];
TestArray3.sort (function () {return Math. random ()> 0.5? -1:1 ;});
Alert (testArray3 );

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.