Although I useJavascriptI have been doing development for many years, but it often has some small features that surprised me. For me, Javascript requires continuous learning. In this article, I will list 10 tips for using Javascript, mainly for beginners and intermediate developers of Javascript. I hope every reader can learn at least one useful technique.
1. Variable Conversion
It looks simple, but as I can see, using constructors such as Array () or Number () for variable conversion is a common practice. Always use the original data type (also called literal) to convert the variable, which is more efficient without any additional impact. Www.phperz.com
- varmyVar ="3.14159",
- str =""+ myVar,// to string
- int= ~~myVar,// to integer
- float= 1*myVar,// to float
- bool = !!myVar,/* to boolean - any string with length
- and any number except 0 are true */
- array = [myVar];// to array
The new Date (myVar) and regular expression (new RegExp (myVar) must use constructors and use the/pattern/flags format when creating regular expressions.
2. Convert decimal to hexadecimal or octal, or vice versa.
Do you want to write a separate function to convert hexadecimal or octal? Stop now! There are more easily available functions available: PHP programmer site
- (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" => 255
- parseInt(string,8)// converts octal to int, eg. "20" => 16
3. Play with numbers
In addition to the previous section, here are more tips for dealing with numbers: www.phperz.com
- 0xFF;// Hex declaration, returns 255
- 020;// Octal declaration, returns 16
- 1e3;// Exponential, same as 1 * Math.pow(10,3), returns 1000
- (1000).toExponential();// Opposite with previous, returns 1e3
- (3.1415).toFixed(3);// Rounding the number, returns "3.142"
4. Javascript version check
Do you know which version of Javascript your browser supports? If you do not know, go to Wikipedia to check the Javascript version table. For some reason, some features of Javascript 1.7 are not widely supported. However, most browsers support the features of version 1.8 and 1.8.1. Note: All Internet Explorer IE8 or older versions) only support Javascript version 1.5. Here is a script that can detect the JavaScript version by detecting features, it can also check the features supported by specific Javascript versions.
- varJS_ver = [];
- (Number.prototype.toFixed)?JS_ver.push("1.5"):false;
- ([].indexOf && [].forEach)?JS_ver.push("1.6"):false;
- ((function(){try{[a,b] = [0,1];returntrue;}catch(ex) {returnfalse;}})())?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"));
5. Use window. name for simple session Processing
This is what I really like. You can specify a string as the value of the window. name attribute until you close the tag or window. Although I have not provided any scripts, I strongly recommend that you make full use of this method. For example, switching between debugging and testing modes is very useful when building a website or application.
6. determine whether an attribute exists
This issue involves two aspects: Checking attributes and obtaining attribute types. However, we always ignore these small things:
- // BAD: This will cause an error in code when foo is undefined
- www.phperz.com if(foo)
- { doSomething(); }
- // GOOD: This doesn't cause any errors. However, even when
- // foo is set to NULL or false, the condition validates as trueif(typeoffoo !="undefined")
- {doSomething();} down.phperz.com
- // BETTER: This doesn't cause any errors and in addition
- // values NULL or false won't validate as trueif(window.foo)
- {doSomething();}
However, in some cases, when we have a deeper structure and need a more appropriate check, we can do this:
- // UGLY: we have to proof existence of every
- // object before we can be sure property actually exists
- if(window.oFoo && oFoo.oBar && oFoo.oBar.baz) {
- doSomething();
- }
7. Pass parameters to the Function
When a function has both required and optional parameters, we may do this:
- functiondoSomething(arg0, arg1, arg2, arg3, arg4) {
- ...
- }
- doSomething('','foo', 5, [],false);
Passing an object is always easier than passing a bunch of parameters:
- functiondoSomething() {
- // Leaves the function if nothing is passed
- if(!arguments[0]) {
- returnfalse;
- }
- varoArgs = 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
- });
This is just a simple example of passing an object as a parameter. For example, we can declare an object, the variable name as the Key, and the default Value as the Value.
8. Use document. createDocumentFragment ()
You may need to dynamically append multiple elements to the document. However, inserting them directly into the document will cause this document to be re-deployed each time. On the contrary, you should use the document fragments and add them only once after they are built:
- FunctiondoSomething (arg0, arg1, arg2, arg3, arg4 ){
- ...
- }
- DoSomething ('', 'foo', 5, [], false );
- Passing an object is always easier than passing a bunch of parameters:
- FunctioncreateList (){
- VaraLI = ["first item", "second item", "third item", "fourth item", "fith item"];
- // Creates the fragment
- VaroFrag = document. createDocumentFragment ();
- While (aLI. length ){
- VaroLI = document. createElement ("li ");
- // Removes the first item from array and appends it
- // As a text node to LIelement
- OLI. appendChild (document. createTextNode (aLI. shift ()));
- OFrag. appendChild (oLI );
- }
- Document. getElementById ('myul '). appendChild (oFrag );
- }
9. Pass a function for the replace () method
Sometimes you want to replace a part of the String with other values. The best way is to pass an independent function to String. replace. PHP programmer site
The following is a simple example of achieving massive output in online poker games:
- varsFlop ="Flop: [Ah] [Ks] [7c]";
- varaValues = {"A":"Ace","K":"King",7:"Seven"};
- varaSuits = {"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 ");
- returnmatch;
- });
- // string sFlop now contains:
- // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"
10. Use of tags in a loop
Sometimes, a loop is nested in the loop. If you want to exit in the loop, you can use the tag:
- outerloop:
- for(variI=0;iI<5;iI++) {
- if(somethingIsTrue()) {
- // Breaks the outer loop iteration
- breakouterloop;
- }
- innerloop:
- for(variA=0;iA<5;iA++) {
- if(somethingElseIsTrue()) {
- // Breaks the inner loop iteration
- breakinnerloop;
- }
- }
- }
We hope that the above content will help you.