Seven Notes for beginners of JavaScript (1)

Source: Internet
Author: User

(1) simplified code

It is very simple to define objects and arrays in JavaScript. We want to create an object, which is generally written as follows:

 
 
  1. var car = new Object();  
  2. car.colour = 'red';  
  3. car.wheels = 4;  
  4. car.hubcaps = 'spinning';  
  5. car.age = 4; 

The following statement can achieve the same effect:

 
 
  1. var car = {  
  2.     colour:'red',  
  3.     wheels:4,  
  4. hubcaps:'spinning',  
  5. age:4  

The subsequent statement is much shorter, and you do not need to repeat the object name.

In addition, there is a simple way to write arrays. In the past, we declared arrays as follows:

 
 
  1. var moviesThatNeedBetterWriters = new Array(  
  2.   'Transformers','Transformers2','Avatar','Indiana Jones 4' 
  3. ); 

A more concise statement is as follows:

 
 
  1. var moviesThatNeedBetterWriters = [  
  2.   'Transformers','Transformers2','Avatar','Indiana Jones 4' 
  3. ]; 

For arrays, there is also a special thing like associating arrays. You will find that many codes define objects as follows:

 
 
  1. var car = new Array();  
  2. car['colour'] = 'red';  
  3. car['wheels'] = 4;  
  4. car['hubcaps'] = 'spinning';  
  5. car['age'] = 4; 

This is crazy. Don't be confused. "Join array" is just an alias of an object.

Another way to simplify the code is to use the ternary operator. For example:

 
 
  1. var direction;  
  2. if(x < 200){  
  3.   direction = 1;  
  4. } else {  
  5.   direction = -1;  

We can replace this statement with the following code:

 
 
  1. var direction = x < 200 ? 1 : -1; 

(2) Use JSON as the data format

The great Douglas Crockford invented the JSON data format to store data. You can use the native javascript method to store complex data without any extra conversion. For example:

 
 
  1. var band = {  
  2.   "name":"The Red Hot Chili Peppers",  
  3.   "members":[  
  4.     {  
  5.       "name":"Anthony Kiedis",  
  6.       "role":"lead vocals" 
  7.     },  
  8.     {  
  9.       "name":"Michael 'Flea' Balzary",  
  10.       "role":"bass guitar, trumpet, backing vocals" 
  11.     },  
  12.     {  
  13.       "name":"Chad Smith",  
  14.       "role":"drums,percussion" 
  15.     },  
  16.     {  
  17.       "name":"John Frusciante",  
  18.       "role":"Lead Guitar" 
  19.     }  
  20.   ],  
  21.   "year":"2009" 

You can use JSON directly in JavaScript, or even as a format returned by the API, which is applied in many APIs, for example:

 
 
  1. <div id="delicious"></div><script>  
  2. function delicious(o){  
  3.   var out = '<ul>';  
  4.   for(var i=0;i<o.length;i++){  
  5.     out += '<li><a href="' + o[i].u + '">' +  
  6.            o[i].d + '</a></li>';  
  7.   }  
  8.   out += '</ul>';  
  9.   document.getElementById('delicious').innerHTML = out;  
  10. }  
  11. </script>  
  12. <script src="http://feeds.delicious.com/v2/json/codepo8/javascript?count=15&callback=delicious"></script> 

Call delicious's Web service to obtain the latest bookmarks, return them in JSON format, and display them as Unordered Lists.

In essence, JSON is the most lightweight way to describe complex data and runs directly in a browser. You can even call the json_decode () function in PHP to use it.

(3) Try to use JavaScript native functions

To find the maximum number in a group of numbers, we may write a loop, for example:

 
 
  1. var numbers = [3,342,23,22,124];  
  2. var max = 0;  
  3. for(var i=0;i<numbers.length;i++){  
  4.   if(numbers[i] > max){  
  5.     max = numbers[i];  
  6.   }  
  7. }  
  8. alert(max); 

In fact, the same function can be implemented without loops:

 
 
  1. var numbers = [3,342,23,22,124];  
  2. numbers.sort(function(a,b){return b - a});  
  3. alert(numbers[0]); 

The simplest method is:

 
 
  1. Math.max(12,123,3,2,433,4); // returns 433 

You can even use Math. max to check the attributes supported by the browser:

 
 
  1. var scrollTop= Math.max(  
  2.  doc.documentElement.scrollTop,  
  3.  doc.body.scrollTop  
  4. ); 

If you want to add a class style to an element, the original method may be as follows:

 
 
  1. function addclass(elm,newclass){  
  2.   var c = elm.className;  
  3.   elm.className = (c === '') ? newclass : c+' '+newclass; 

The more elegant method is:

 
 
  1. function addclass(elm,newclass){  
  2.   var classes = elm.className.split(' ');  
  3.   classes.push(newclass);  
  4.   elm.className = classes.join(' ');  


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.