JavaScript Learning---JavaScript basics

Source: Internet
Author: User
Tags throw exception

How JavaScript is introduced

How JavaScript is introduced:

1. Write directly in script;

2. Use <script src= "JS file location" >

{#1 write directly #}    <script>        alert (' Hello Yuan ')    </script>{#2 import File #}    <script src= "Hello.js" ></script >
Specifications for JavaScript

Specifications for JavaScript

1. Variables: 0 variables are weakly typed (very casually); 1 declare variables without declaring variable types.      All use the var keyword;   var A;        21 rows can declare multiple variables. And can be of different types.   var name= "Hello", age=20, job= "lecturer"; 3 (understand) You can declare variables without var.   If you do not use Var then it is a global variable.          4 variable name, the first character can only be letters, underscores, $ US dollar symbol Three select one, and case-sensitive, x and X is two variables, not the keyword 5 generally we have to seal the end of the symbol, the specification must be written; The default is a newline character is the end flag 6 variable should also follow one of the following famous naming rules:    var s = "HelloWorld";    "Camel notation: First letter lowercase, the remaining words capitalized" var s = "HelloWorld";   "Pascal notation: initial capitalization, the remaining words capitalized" "Recommended" var s = "Shelloworld";    "Hungarian type notation: use s for string type, with I for INT type, first capitalization" Note: No VAR is represented by global variable 2. NOTE: Multi-line comments and single-line comments are supported.    Single-line comment://var = "Hello";                Multiline Comment:/* var= "Hello";            Var= "World"; */3. Code Printing: alert (' Hello World ') document.write (' Hello Wrold ') consol.log (' Hello World ') 4. Constants and flag constants: Data that appears directly in the program Value identifiers: The names of letters, numbers, underscores (_), Dollar signs ($) that do not start with a number are commonly used to denote functions, variables, and so on. A word that represents a specific meaning in a JavaScript language is called a reserved word and does not allow a program to be redefined as an identifier

Data type

Data type:

Basic data type: Number String Boolean null[Object] undefined[system]

Reference data types: Functions, arrays, objects, etc.

Basic data type:

Numeric type: A 10-binary integer in JavaScript consists of a sequence of numbers    that    is an integer floating-point string:   a sequence of string constants consisting of Unicode characters, numbers, and punctuation marks that are    surrounded    by single or double quotation marks Common escape characters \ n: newline  \ ': Single quotation mark   \ ': double quote \  \: Right-underlined Boolean:    Boolean type has only two values: True and False, also representing 1 and 0, in the actual operation True=1,false=0    Boolean values can also be considered as on/off, yes/no, 1/0 corresponds to true/falseundefined:    The Undefined type has only one value, which is Undefined. When the declared variable is not initialized, the default value of the variable is undefined.    when the function has no definite return value, the returned value is also "undefined"; Null type    It has only one private value, NULL, which is used to save the object, the default is the type of object, typeof (NULL) Note:    undefined is the value assigned to the variable when it is declared but not initialized, and the system assigns  var STR;    Null is used to represent an object that does not already exist, which the developer does

Data type conversions

JavaScript is a loosely typed program language variable that does not need to specify a data type variable at the time of declaration it is determined that the data type expression contains different types of data when it is assigned, and the class conversions are enforced during the calculation. Number + String:  number converted to string number + Boolean value:  true converts to 1,false to 0;   Alert (1+ture)--2  [true=1] String + Boolean value: Boolean converted to string true or false; alert (' Hello ' +true)--Hellotrue

Forcing data type conversions

function parseint:   cast to an integer, if non-numeric, displays nan,not a number, with self-reported false  such as parseint ("6.12") =6  ; parseint ("12a") =12; parseint ("A12") =nan  ;p arseint ("1a2") =1 function parsefloat: Cast to floating-point number  parsefloat ("6.12") =6.12 function eval:       Casts a string to an expression and returns the result   for example: eval ("=2"), eval ("1<2") =true
Operator

Operator:

Base algorithm plus (+), minus (-), multiplication (*), except (/), remainder (%) plus, minus, multiply, divide, remainder, and mathematical methods such as: 9/2=4.5,4*5=20,9%2=1-in addition to representing a minus sign can also represent a negative sign for example: X=-y+ can also represent addition operations     Connections for strings such as: "ABC" + "def" = "abcdef" self-increment/decrement var i=1;console.log (i++);     At this time i=2, print: I=1console.log (++i);     At this time i=2, complete ++i, I=3console.log (i--);     At this time i=2, print i--=3console.log (--); Print 1console.log (i)//print $11 Add//var a=3 #此时b = 3, and the value is Number//var a=3.2 #此时b = 3.2, and the value is Number//var a= ' 3.2 ' # At this time b=3.2, and the value is Number//var a= ' 123a456 ' #此时为b =nan, non-numeric var a= ' Hello ' # fee string var b+=aalert (typeof (b)) Conclusion: unary addition can realize the conversion of string, If it is number, it will not change, if it is a numeric string type, it will be changed to # Type, and when a string is encountered, the conversion fails with the Nan logical operator equal to (= =), not equal to (! =), greater than (>), less than (<)? =), less than or equal (<=) and (&&), or (| |), non-(!) --------------------------------------------------------------------------------------------Logical AND The operand of an operation can be of any type, not just a Boolean value. If an operand is not the original Boolean value, the logical AND operation does not necessarily return a Boolean value: If an operand is null, NULL is returned. If an operand is Nan, a nan is returned. If one of the operands is undefined, return to undefined. 1 && 1 = 1 1 | | 1 = one &AMP;&Amp 0 = 0 1 | | 0 = && 0 = 0 0 | | 0 = 0

The assignment operator and the all equals = Delegate assignment two equals = = to determine equality, if there is a string and an integer comparison, the integer is converted to a string to compare three equals = = = All equals, if there is a comparison of strings and integers, the integer is not converted to a string for comparison 2== ' 2 '  -- >true2=== ' 2 '-->false the rules for performing type conversions are as follows:    If an operand is a Boolean value, convert it to a numeric value before checking for equality. False converts to 0,true to 1.    if one operand is a string and the other is a number, try converting the string to a number before checking for equality.    if one operand is an object and the other is a string, try to convert the object to a string before checking for equality.    if one operand is an object and the other is a number, try converting the object to a number before checking for equality. In comparison, the operator also adheres to the following rules:    values null and undefined are equal.    when checking for equality, null and undefined cannot be converted to other values.    If an operand is NaN, the equal sign returns false, and the non-equal sign returns TRUE.    if the two operands are objects, then their reference values are compared. If two operands point to the same object, then the equals sign returns TRUE, otherwise two operands are not equal.

Why is switch higher efficiency than if-else?

The 1.switch is used to route multiple branches based on an integer value, and the compiler can optimize the 2.switch-case to evaluate the expression only once, then compare the value of the expression to the value of each case, and then select the statement block 3.if that executes which case: Else the judgment of the scope of a wide range, each statement is basically independent, each time you judge the condition to load 1 times. So use the switch ratio if in the multi-channel branch. else if: Else structure is highly efficient.

For loop

Method One: Python-like non-canonical for loop var a = [123 ']for (var i in a) {    alert (i)  //0 1 2 Print key value    alert (A[i])//Print value, array-like Operation}/ /Method Two: Specification for loop    [recommended format]var b= [, ' 123 ']for (var i=0;i<3;i++) {    alert (B[i])}//for loop Support: operation of JSON data var x={"Hello ":" World "," good ":" Morning "," arr ": [1,2,3]}alert (typeof (X))   //Objectalert (x)            //Object:objectfor (var i in X) {    alert (X[i])  //World Morning

While Loop : For loops that already know the number of cycles

-------------------while Loop------------------var i=1;var ret=0;while (i<101) {    ret+=i;    i++;      Control variable}alert (ret)

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 is used to point to an Error object or other thrown object}finally {//Whether or not the code in the     try is thrown (even if there is a return statement in the try code block), the finally code block is always executed. } Note: Throw exception throw error (' xxxx ')
try{    var b=123;    alert (b);    throw new Error ("Hello")    return 666}catch (e) {    alert (e);} Finally {    alert ("success!")

JavaScript Learning---JavaScript basics

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.