JavaScript syntax, variable types, conditions, looping statements, functions, object-oriented

Source: Internet
Author: User
Tags constant math natural logarithm square root

1. There are two forms of JavaScript code leather:

<!--way a--><script type='txt/javascript' src='/js/comment.js  '></script><!--way two--><script type='txt/javascript' >    JS code content </script>

Method one can effectively improve the reusability of code

2, JavaScript code storage location

    • In the head of HTML
    • The bottom of the body code block of HTML (recommended)

Because the HTML code is executed from top to bottom, if the JS code in the head is time consuming, it will cause the user to be unable to see the page for a long time, if it is placed at the bottom of the body code block, the above HTML code is loaded, then even if the JS code is time consuming, it will not affect the user to see the page Just JS to achieve the effect of slow.


One, variable

The declaration of a variable in JavaScript is a very error-prone point, a local variable must start with a Var, and if Var is not used, the default is to declare a global variable.

<script type="text/javascript">     //  global variables    ' Seven ' ;     function func () {        //  local variable        var;          // Global Variables        " male "     }</script>

Code comments in javascript:

    • Single-line//
    • Multi-Line/* * *   Note: This comment takes effect only in the script block.   

ii. Types of data

The data types in JavaScript are divided into primitive types and object types:

    • Original type
      • Digital
      • String
      • Boolean value
    • Object type
      • Array
      • Dictionary
      • ...

In particular, numbers, booleans, nulls, undefined, and strings are immutable.

1. Numbers (number)

In JavaScript, integer values and floating-point values are not distinguished, and all numbers in JavaScript are represented by floating-point numbers.

Transformation:

    • parseint (..) Converts a value to a number, or Nan if unsuccessful
    • Parsefloat (..) Converts a value to a floating-point number, or Nan if unsuccessful

Special values:

    • NaN, not a number. Can be judged using IsNaN (num).
    • Infinity, infinitely large. Can be judged using isfinite (num).

More numerical calculations:

constant MATH.E constant E, base of natural logarithm. The natural logarithm of the math.ln1010. The natural logarithm of the math.ln22. math.log10e the logarithm of E with a base of 10. MATH.LOG2E the logarithm of E with a base of 2. MATH.PI constant figs/u03c0.gif. The square of the math.sqrt1_22 is eradicated with 1. The square root of the math.sqrt22. The static function Math.Abs () calculates the absolute value. Math.acos () calculates the inverse cosine value. Math.asin () calculates the inverse chord value. Math.atan () calculates the inverse tangent value. Math.atan2 () calculates the angle from the x-axis to a point. Math.ceil () rounds a number. Math.Cos () calculates the cosine value. Math.exp () calculates the exponent of E. Math.floor () to a number of people. Math.log () calculates the natural logarithm. Math.max () returns the larger of the two numbers. Math.min () returns the smaller of the two numbers. Math.pow () calculates XY. Math.random () calculates a random number. Math.Round () is rounded to the nearest integer. Math.sin () calculates the sine value. MATH.SQRT () calculates the square root. Math.tan () calculates the tangent value. 
View Code

2. Strings (String)

A string is an array of characters, but in JavaScript the string is immutable: You can access text anywhere in the string, but JavaScript does not provide a way to modify the contents of a known string.

Common features:

var name = "wupeiqi" ; var name = String( "wupeiqi" ); var age_str = String( 18 ); 常用方法:      obj.trim()      obj.charAt(index)      obj.substring(start,end)      obj.indexOf(char)      obj.length
Obj.substring (from, to),obj.slice (start, end) index before fetching

3. Boolean Type (Boolean)

The Boolean type contains only true and false, unlike Python, whose first letter is lowercase.

    • = = Compare Values equal
    • ! = does not equal
    • = = = Comparison value and type are equal
    • !=== Not equal to
    • || Or
    • && and

4. Arrays

Arrays in JavaScript are similar to lists in Python

Common features:

1 the size of the obj.length array2  3 Obj.push (ele) trailing append element4 obj.pop () tail gets an element and deletes it in obj5 Obj.unshift (ele) head insertion element6 obj.shift () tail gets an element and deletes it in obj 7 Obj.splice (Start, DeleteCount, value, ...) Inserting, deleting, or replacing elements of an array8Obj.splice (N,0, Val) to specify the position to insert the element9Obj.splice (N,1, Val) to specify the position substitution elementTenObj.splice (N,1) to specify the location to delete the element One obj.slice () slices A obj.reverse () reversal - obj.join (Sep) joins the array elements to construct a string. - Obj.concat (Val,..) Connection Array theObj.sort () sorting an array element

5. Serialization

    • Json.stringify (obj) serialization
    • Json.parse (str) deserialization
Iii. Statements and exceptions

1. Conditional statements

JavaScript supports two medium conditional statements, namely: if and switch

    if (condition) {     }Elseif(condition) {             }else{     }
    Switch(name) { Case '1': Age=123;  Break;  Case '2': Age=456;  Break; default: Age=777; }

2. Circular statements

JavaScript supports three loop statements, namely:

 1  var  names = [  " alex   ", "  tony   ", "  rain   " ];  2  3  for  (var  i=0 ; i<names.length;i++<    Span style= "color: #000000") { 4   Console.log (i);  5   Console.log (Names[i]);  6 } 
way one
 1  var  names = [  " alex   ", "  tony   ", "  rain   " ];  2  3  for  (var  index in   names) { 4   Console.log (index);  5   Console.log (Names[index]);  6 } 
Mode two
1  while (condition) {2     // Break ; 3     // continue; 4 }
Way Three

3. Exception Handling

Try {    // This piece of code runs from top to bottom, where any one of the statements throws an exception the code block ends running }catch  (e) {     // If an exception is thrown in a try code block, the code in the catch code block is executed.     // e is a local variable that points to an error object or other thrown object }finally  {     // whether the code in the try is thrown unexpectedly (even if there is a return statement in the try code block), The finally code block is always executed. }

Note: Actively run out of exception throw Error (' xxxx ')

Iv. functions

1. Basic functions

The functions in the

JavaScript can basically be divided into three categories:

 //  normal function   function func (ARG) { return  true     Span style= "COLOR: #000000" >;  //  anonymous function  var  func = function (ARG) { return
      " tony   "    ;      //  self-executing function      (function (ARG) {console.log (ARG); }) (  " 123   ' ) 

2. Object-oriented

1 function Foo (name,age) {2      This. Name =name;3      This. Age =Age ;4      This. Func =function (ARG) {5         return  This. Name +Arg;6     }7 }8   9 varobj =NewFoo ('Alex', -);Ten varret = obj. Func ("SB"); OneConsole.log (ret);

You need to be aware of the above code:

    • Foo acts as a constructor
    • This refers to the object
    • When creating an object, you need to use the new

Each object in the preceding code holds an identical func function, wasting memory. Use the prototype and you can resolve the problem:

function Foo (name,age) {    this. name = name;     this. Age == {    getinfo:function ()}        {returnthis this. Age    },    func:function (ARG) {        returnthis. Name + arg;}    }

JavaScript syntax, variable types, conditions, looping statements, functions, object-oriented

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.