JavaScript learning Summary-tips, practical functions, concise methods, programming details, javascript details
Sort out some JavaScript skills, practical functions, and common function implementation methods for reference only
Variable Conversion
//edit http://www.lai18.com var myVar = "3.14159",str = ""+ myVar,// to stringint = ~~myVar, // to integerfloat = 1*myVar, // to floatbool = !!myVar, /* to boolean - any string with lengthand any number except 0 are true */array = [myVar]; // to array
However, the conversion Date (new Date (myVar) and regular expression (new RegExp (myVar) must use constructors, use a simplified form such as/pattern/flags when creating a regular expression.
Converts an integer to a numeric value.
// Edit http://www.lai18.com // when a numeric variable is involved in the computation, JS automatically converts it to a numeric value (if it cannot be converted to NaN) '10. 567890 '| 0 // result: 10 // All numeric types in JS are double-precision floating-point numbers. Therefore, when JavaScript performs bitwise operations, it first converts these numeric values to integers, then execute the operation // | is binary or, x | 0 is always equal to x; ^ is an exclusive or, with 0 different from 1, so x ^ 0 is always equal to x; as ~ It is bitwise inversion. After two operations, the value is of course the same '10. 100' ^ 0 // result: 10-567890 | 0 // result:-2 ~~ -2.23456789 // result:-2
Date to numeric value
// The internal representation of JS time is the Unix timestamp, recording the current time unit var d = + new Date () from, January 1, January 1, 1970 in milliseconds; // 1295698416792
Class array object to array
var arr =[].slice.call(arguments)
The following instances are used more absolutely
Function test () {var res = ['item1', 'item2'] res = res. concat (Array. prototype. slice. call (arguments) // method 1 Array. prototype. push. apply (res, arguments) // method 2}
Conversion between hexadecimal
(int).toString(16); // converts int to hex, eg 12 => "C"(int).toString(8); // converts int to octal, eg. 12 => "14"parseInt(string,16) // converts hex to int, eg. "FF" => 255parseInt(string,8) // converts octal to int, eg. "20" => 16
Insert an array to the specified position of another Array
var a = [1,2,3,7,8,9];var b = [4,5,6];var insertIndex = 3;a.splice.apply(a, Array.prototype.concat(insertIndex, 0, b));
Delete array elements
var a = [1,2,3,4,5];a.splice(3,1); //a = [1,2,3,5]
You may wonder why you need to use splice instead of delete, because using delete will leave a hole in the array, and the subsequent subscript is not decreasing.
Judge whether it is IE
var ie = /*@cc_on !@*/false;
In this case, you can determine whether it is ie or not...
In fact, there are more wonderful methods, please refer to the following
// Edit http://www.lai18.com // seems to be the shortest, using IE does not support the standard ECMAscript array at the end of the comma ignore the mechanism var ie =! -[1,]; // uses the IE condition to comment out var ie =/* @ cc_on! @ */False; // or conditional annotation var ie // @ cc_on = 1; // IE does not support vertical tabs var ie = '\ V' = 'V '; // Same principle as var ie =! + "\ V1 ";
When I learned this, I felt weak.
Use native methods whenever possible
To find the maximum number in a group of numbers, we may write a loop, for example:
var numbers = [3,342,23,22,124];var max = 0;for(var i=0;i<numbers.length;i++){ if(numbers[i] > max){ max = numbers[i]; }}alert(max);
In fact, the native method can be used for simpler implementation.
var numbers = [3,342,23,22,124];numbers.sort(function(a,b){return b - a});alert(numbers[0]);
Of course, the simplest method is:
Math.max(12,123,3,2,433,4); // returns 433
This can also be done now
Math. max. apply (Math, [12,123, 3, 2,433, 4]) // obtain the maximum Math value. min. apply (Math, [12,123, 3, 2,433, 4]) // obtain the minimum value.
Generate random number
Math. random (). toString (16). substring (2); // the parameter of the toString () function is the base, range: 2 ~ 36. Math. random (). toString (36). substring (2 );
No third-party variables are required to exchange values of two variables.
a=[b, b=a][0];
Event Delegate
For example, the html code is as follows:
The js Code is as follows:
// Classic event handling example(function(){ var resources = document.getElementById('resources'); var links = resources.getElementsByTagName('a'); var all = links.length; for(var i=0;i<all;i++){ // Attach a listener to each link links[i].addEventListener('click',handler,false); }; function handler(e){ var x = e.target; // Get the link that was clicked alert(x); e.preventDefault(); };})();
Event delegates can be used to write more elegant:
(function(){ var resources = document.getElementById('resources'); resources.addEventListener('click',handler,false); function handler(e){ var x = e.target; // get the link tha if(x.nodeName.toLowerCase() === 'a'){ alert('Event delegation:' + x); e.preventDefault(); } };})();
Check ie version
var _IE = (function(){ var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0] ); return v > 4 ? v : false ;}());
JavaScript version check
Do you know which version of Javascript your browser supports?
var JS_ver = [];(Number.prototype.toFixed)?JS_ver.push("1.5"):false;([].indexOf && [].forEach)?JS_ver.push("1.6"):false;((function(){try {[a,b] = [0,1];return true;}catch(ex) {return false;}})())?JS_ver.push("1.7"):false;([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;("".trimLeft)?JS_ver.push("1.8.1"):false;JS_ver.supports = function(){ if (arguments[0]) return (!!~this.join().indexOf(arguments[0] +",") +","); else return (this[this.length-1]);}alert("Latest Javascript version supported: "+ JS_ver.supports());alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));
Determine whether an attribute exists
// BAD: This will cause an error in code when foo is undefinedif (foo) { doSomething();}// GOOD: This doesn't cause any errors. However, even when// foo is set to NULL or false, the condition validates as trueif (typeof foo != "undefined") { doSomething();}// BETTER: This doesn't cause any errors and in addition// values NULL or false won't validate as trueif (window.foo) { doSomething();}
In some cases, we have a deeper structure and a more appropriate check.
// UGLY: we have to proof existence of every// object before we can be sure property actually existsif (window.oFoo && oFoo.oBar && oFoo.oBar.baz) { doSomething();}
In fact, the best way to check whether a property exists is:
if("opera" in window){ console.log("OPERA");}else{ console.log("NOT OPERA");}
Check whether the object is an array
var obj=[];Object.prototype.toString.call(obj)=="[object Array]";
Passing objects to Functions
function doSomething() { // Leaves the function if nothing is passed if (!arguments[0]) { return false; } var oArgs = arguments[0] arg0 = oArgs.arg0 || "", arg1 = oArgs.arg1 || "", arg2 = oArgs.arg2 || 0, arg3 = oArgs.arg3 || [], arg4 = oArgs.arg4 || false;}doSomething({ arg1 : "foo", arg2 : 5, arg4 : false});
Pass a function for the replace Method
var sFlop = "Flop: [Ah] [Ks] [7c]";var aValues = {"A":"Ace","K":"King",7:"Seven"};var aSuits = {"h":"Hearts","s":"Spades","d":"Diamonds","c":"Clubs"};sFlop = sFlop.replace(/\[\w+\]/gi, function(match) { match = match.replace(match[2], aSuits[match[2]]); match = match.replace(match[1], aValues[match[1]] +" of "); return match;});// string sFlop now contains:// "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"
Use tags in a loop
Sometimes nested loops in a loop, you may want to exit a loop. Before that, you always use a flag variable to determine whether a better method is available.
outerloop:for (var iI=0;iI<5;iI++) { if (somethingIsTrue()) { // Breaks the outer loop iteration break outerloop; } innerloop: for (var iA=0;iA<5;iA++) { if (somethingElseIsTrue()) { // Breaks the inner loop iteration break innerloop; } }}
Deduplication of Arrays
/** @ Desc: deduplicates the array and returns a new array */function unique (target) {var result = []; loop: for (var I = 0, n = target. length; I <n; I ++) {for (var x = I + 1; x <n; x ++) {if (target [x] === target [I]) {continue loop ;}} result. push (target [I]);} return result ;}
Or:
Array.prototype.distinct = function () { var newArr = [],obj = {}; for(var i=0, len = this.length; i < len; i++){ if(!obj[typeof(this[i]) + this[i]]){ newArr.push(this[i]); obj[typeof(this[i]) + this[i]] = 'new'; } } return newArr;}
In fact, the optimal method is as follows:
Array.prototype.distinct = function () { var sameObj = function(a, b){ var tag = true; if(!a || !b) return false; for(var x in a){ if(!b[x]) return false; if(typeof(a[x]) === 'object'){ tag = sameObj(a[x],b[x]); } else { if(a[x]!==b[x]) return false; } } return tag; } var newArr = [], obj = {}; for(var i = 0, len = this.length; i < len; i++){ if(!sameObj(obj[typeof(this[i]) + this[i]], this[i])){ newArr.push(this[i]); obj[typeof(this[i]) + this[i]] = this[i]; } } return newArr; }
Example (borrow comments ):
var arr=[{name:"tom",age:12},{name:"lily",age:22},{name:"lilei",age:12}];var newArr=arr.distinct(function(ele){ return ele.age;});
Searches for the maximum number of characters in a string.
Var I, len, maxobj = '', maxnum = 0, obj = {}; var arr =" sdjksfssscfssdd "; for (I = 0, len = arr. length; I <len; I ++) {obj [arr [I]? Obj [arr [I] ++: obj [arr [I] = 1; if (maxnum <obj [arr [I]) {maxnum = obj [arr [I]; maxobj = arr [I] ;}} alert (maxobj + "appears in the array" + maxnum + "times ");
In fact, there are many other things I just want to summarize.
For more information about JavaScript, refer:
1Regular Expression Summary: Regular Expressions in JavaScript
2JavaScript variable type
3. Have an in-depth understanding of the scope of JavaScript
4 javascript: for Loop (for Loops)
5JavaScript: for-in loop (for-in Loops)
6 javascript: Prototypes is too powerful
7 javascript: var pre-parsing and side effects
8 javascript: Use global variables with caution
9JavaScript exploration: the importance of writing maintainable code
10. How should we understand the working principles of the JavaScript engine?
11JavaScript: Name function expression
12JavaScript: function name in the debugger
13JavaScript: Memory Management of JScript
14JavaScript: function declaration and function expression
15JavaScript: JScript Bug
16JavaScript: eval () is the devil"
17JavaScript: Basic coding specifications
18 JavaScript exploration: Using parseInt () for Numerical Conversion
19JavaScript: Constructor
20 Execution context 1: Variable object and activity object
21 javascript: Prototype chain
22. Execution context 2: Scope chain Scope Chains
23JavaScript: Object
24JavaScript: SpiderMonkey's quirks
25 javascript: naming function expression Substitution Solution
26JavaScript function 2: function expression
27JavaScript function 4: function Constructor
28JavaScript functions 1: function declaration
29JavaScript Function 3: function expressions in a group
30JavaScript: Powerful prototype and prototype chain
31 execution context 4: This pointer
32 Execution context 3: Closure Closures
33JavaScript variable object 3: two stages of execution Context
34JavaScript variable object 2: VO in different execution contexts
35JavaScript variable object IV: Variables
36JavaScript variable object 1: VO Declaration
Property of the 37JavaScript variable object __parent _
38JavaScript scope chain 3: Scope chain features
39JavaScript scope chain 2: function Lifecycle
4040javascript scope chain 1: Scope chain Definition
41JavaScript closure 2: Implementation of closure
42JavaScript closure 1: Introduction to closures
43JavaScript closure 3: Closure usage
44JavaScript Object Access and traversal
Variable pre-parsing features of 45JavaScript
46. New JavaScript Data Structure Streams
47. Javascript anonymous Functions
48 briefly describe JavaScript classes and objects
49JavaScript: some methods for defining classes and objects
50 create a JavaScript hash table Hashtable
51 JavaScript closure features
52. About the prototype attribute of JavaScript
53JavaScript keyword return usage
How does 54JavaScript implement inheritance?
55 clarify JavaScript object-oriented ideas
56. In-depth JavaScript Object creation details
57 explore JavaScript event bubbling
58 do you know JavaScript non-blocking loading scripts?
59 JavaScript Date prototype method extension
60 working principles behind JavaScript prototype
61 a blog post giving a full view of JavaScript
62. JavaScript variable scope
63 gossip JavaScript and Cookies
64 JavaScript reflection examples
65 analyze the garbage collection mechanism of JavaScript
66 non-blocking JavaScript scripts and extended knowledge
Inheritance Mechanism imitation in 67JavaScript
68JavaScript should understand closures first understand lexical scopes
69. in-depth research on the event mechanism of JavaScript
70 understand JavaScript Functions
71JavaScript object learning notes
72 [JavaScript secret garden] Object 1: usage and attributes
73 [JavaScript secret garden] object 2: Ghost prototype