JavaScript learning summary [2] JS Basics

Source: Internet
Author: User
Tags true true
Naming Conventions are necessary to enhance the readability of the Code, so that you can understand what you want to express at a Glance. Standards are rules that make the code easier for later maintenance, it can also greatly improve the development efficiency. A normal website has a lot of JS Code. If you do not follow certain rules during the compilation process, you will not be able to understand what you wrote after writing it. This is a very troublesome thing, therefore, we need to develop a good habit of writing code during regular exercises. 1. JS naming rules

Naming Conventions are necessary to enhance the readability of the Code, so that you can understand what you want to express at a Glance. Standards are rules that make the code easier for later maintenance, it can also greatly improve the development efficiency. A normal website has a lot of JS Code. If you do not follow certain rules during the compilation process, you will not be able to understand what you wrote after writing it. This is a very troublesome thing, therefore, we need to develop a good habit of writing code during regular exercises.

Generally, the Hungarian or camper method is used.

The principle of the Hungarian naming method: variable name = property + Type + object description. The key is to use one or more lower-case letters as the prefix, followed by a combination of one or more upper-case words, which indicates the purpose of the variable.

The first word starts with a lowercase letter, and then the first letter of each word is capitalized. For example, myFirstName and myLastName, the variable name looks like a camper. The key to the hump method is: in addition to the first word, the size of the first letter of other words. The variable name and function name are composed of uppercase and lowercase letters, and the logical breakpoint can be formed by underlines, this improves the readability of the Code.

What naming conventions should be based on personal preferences or company regulations. Note: you cannot use reserved words or names that are too long to remember. Avoid using two similar variable names. The following are the prefixes of commonly used Hungarian naming methods:

2. Notes are important

In JS, "// comment content" is used for single-line comments, and "/* Comment content */" is used for multi-line comments. The function of annotation is to improve the readability of the Code. It is not only convenient for later use, but also helps others to read and understand the JS code you have compiled. The content of the comment will not be displayed on the webpage. For ease of reading, comments are generally placed at or around the end of the statement to be interpreted. In the process of learning, we should develop a good habit of writing comments, which is conducive to our understanding of the Code, or mark the vague concept at that time, and then conduct in-depth targeted learning, better grasp of this knowledge point.

3. JS statements and symbols

The JS statement is a command sent to the browser. These commands are used to tell the browser what to do. The execution rules of JS are in the unit of action from top to bottom. Generally, each row is a statement. For example, var a = 1 + 2. This statement first declares variable a with the var keyword, and then assigns the result of 1 + 2 to variable. Note that the = symbol is not equivalent to an equal sign in JS, but a value is assigned. For example: alert ('hello'); this is a JS statement. The end of a row is regarded as the end of the statement. Generally, A; is added at the end to indicate the end of the statement, if multiple lines of JS statements exist and each sentence ends, the statements are executed in order. Note: The Code and symbols in JS must be entered in English. You can leave them empty, but errors may occur, the browser will determine that the previous sentence and the last sentence can be connected and explained together, which leads to some unexpected errors. We need to develop good programming habits, remember not to forget to add the points where the points must be added.

JS is sensitive to the size. When writing JavaScript code, you need to pay attention to whether the case-sensitivity switch is disabled.

4. JS judgment statement and for Loop

If judgment statements and for loops are frequently used in JS.

When writing code, you always need to execute different actions for different decisions. In the code, you can use the if Condition Statement to complete the task.

In JS, you can use the following conditional statements:

(1) if statement: only code executed when the specified condition is true, that is, when the condition is set.

(2) if... else statement: the code after executing if when the condition is set and the condition is false.

(3) if... else statement: This statement is used to select one of multiple code blocks for execution based on the judgment conditions.

Example: different greetings are prompted at different times. When the time is less than 12, good morning greetings, and when the time is greater than or equal to 12 or less than 18, good afternoon greetings, otherwise, all greetings to good evening.

Script var d = new Date (); var time = d. getHours (); if (time <12) {alert ('Good morning ');} else if (time >=12 & time <18) {alert ('good afternoon ');} else {alert ('Good evening');} script

If you want to run the same code over and over again, and each time the values are different, it is very convenient to use the loop. When there is a group of elements, you can use the for loop to add events to this group of elements.

For Loop Syntax:

For (Statement 1; Statement 2; Statement 3) {executed code block} Statement 1 is used to initialize all variables in the loop. Usually: var I = 0; Statement 2 is used to set the conditions for initial variables. Usually: I
 
  

Instance: cyclically traverses the data in the array and outputs the data in sequence:

// When loop is not used, we can output the values in the array as follows: var cars = ["Land Rover", "BMW", "Mercedes-Benz", "Audi", "Buick ", "public"]; document. write (cars [0] +"
"); Document. write (cars [1] +"
"); Document. write (cars [2] +"
"); Document. write (cars [3] +"
"); Document. write (cars [4] +"
"); Document. write (cars [5] +"
"); // Use the for loop to compact the output: for (var I = 0, I ");}

Document. write () can be used to directly output the stream content to HTML. It can be used to output the content test code to the page during normal exercises. Pay attention to document here. write () must output the write content to the document. If the document has been loaded and then runs this statement, the entire page will be overwritten. If document. write () is placed in an event, all content on the page is cleared and then written.

5. Some basic concepts of JS

(1) identifier: an identifier is a symbol defined in Javascript. It can consist of uppercase/lowercase letters, numbers, underscores, and dollar signs ($) in any order. An identifier is the name of a specific object. The most common identifier is the variable name and function name. JS is case sensitive, so A and a are two different identifiers. The identifier cannot start with a number or be a reserved keyword in JS. For details, refer to Baidu references. There are three other words that are not reserved, but they cannot be used as identifiers due to their special meanings: Infinity, NaN, and undefined.

(2) code block: it is not difficult to understand the code block. The following JavaScript code is the sequence of JS statements. The Browser executes each statement line by line based on the sequence of JS statements, the code block is a combination of JS statements and is contained in curly brackets. The function of the code block is to tell the browser to execute the statement sequence together. JS functions are typical examples of combining statements in blocks.

(3) variables: literally, variables are the amount that can be changed, but from the programming point of view, variables are the "containers" used to store some or some numerical information ", simply put, it is a reference to a value. Using a variable is equivalent to referencing a value. Each variable has a variable name. For example: var x = 1; declare a variable x first, and x is the variable name, then assign a value with =, that is, assign 1 to x. Later, when referencing x, the value 1 is returned. Creating a variable in JS is usually called a "Declaration" variable. var is used to declare the variable. The variable is empty after declaration, and its value is undefined (undefined). It needs to be assigned a value before use. = is used to establish this reference relationship. The code above can be viewed as: var x; x = 1; in this case, a variable is first declared and assigned a value. The code above is assigned a value while being declared. In a statement, multiple variables can be declared and separated by commas. Note: JS keywords and JS reserved words cannot be used when naming variables.

(4). Constant: a constant is generated when a variable exists. A variable can be understood as a variable, while a constant is a constant. In fact, there is no constant in JS. The so-called constant is just a variable assigned in advance. Constants and variables belong to variables, but constants cannot be changed after being assigned. Normal variables can be assigned again. To distinguish it from variables and enhance code readability, when declaring a constant, the constant name is generally capitalized. If multiple words exist, they can be separated by underscores.

(5) literal volume: the so-called literal volume is actually the representation of an object, or the creation method. It is not a value, but a way to express a value, simply put, a literal is how to express the value of an object. When assigning values to a variable, all values after the assignment operator can be considered as a literal. A literal can also be considered as a constant, such as 100. Note: A variable is a name, while a literal is a value. The literal can be divided into numeric literal, string literal, and expression literal. The literal number, which can be an integer or a decimal number. For example, var a = 10; var B = 3.14; 10 and 3.14 are the literal numbers. String literal, a series of characters enclosed by quotation marks. For example, var str = 'xiaoming '; 'xiaoming' is the string literal. The expression literal can be divided into array literal, object literal, and function literal. Array literal, separated by commas (,). For example, var arr = [1, 2, 3, 4, 5, 6]; [1, 2, 3, 4, 5, 6] indicates the array literal. The object literal is a combination of key-value pairs. Each key-value pair is separated by a comma and included in curly brackets. For example: var obj = {a: 12, B: 5, c: '21'}, {a: 12, B: 5, c: '21'} is the object literal. Function literal, function myFunction (a, B) {return a * B ;} A function literal is composed of an optional function name after the function keyword is used, a parameter enclosed in parentheses, and an execution statement enclosed in curly brackets. A function is an expression rather than a statement. The preceding example can be written as var myFunction = function (a, B) {return a * B;}, which is easy to understand, it can also be said that the literal value of a function is an anonymous function, which points to who uses it.

(6) Scope of variables: variables are classified into global variables and local variables. A global variable is a variable declared outside a function. It can be used anywhere. A local variable is a variable declared inside a function and can only be used inside a declared function. This is the scope of the variable, and the common understanding is its scope of action. The lifecycle of JS variables starts when they are declared. global variables are deleted after the page is closed, and local variables are deleted after the function is run.

(7) Expressions: expressions are similar to definitions in mathematics. They are algebraic computation expressions that have certain values and use operators to connect constants and variables, an expression can contain constants or variables. For example, var a = a + 1; a is the variable name, and a + 1 is the expression. There are many forms of "goodbye" expressions in life, such as goodbey, 886, and body language. Expressions in JS are everywhere and can express the following types of content: String connection, called a string expression, var str = "I" + "love" + "you"; and this form: var str = "hello"; var str1 = str + "World"; the string expression value is a string. Value expression: var num = 10 + 2.5; also in the following form: var num = 10 + 2.5; var num1 = num + 10*2.5; value expression value is a value. There is also a Boolean expression, var num = 2; alert (num = 2); returns true, alert (num> 10); returns false. The Boolean expression value is true or false.

(8) functions: When you see a function, many people may have a headache, but functions in programming are quite understandable, it is an event-driven or reusable code block executed when it is called. Simply put, it is a set of statements to complete a specific function. The function keyword is used to define the block of code enclosed in curly brackets, which is convenient for repeated calls. The basic form is: function moveStart () {code }. Declaring a function only tells the browser that there is a function that will not be actually executed, but the code in the function is actually executed when the function is called. MoveStart is the function name. It follows the JS naming rules and is used when calling a function: moveStart (). If a function is defined after a variable, the variable can be used as a function. The function is stored in the Variable. You can call the function by using the variable name without the function name. We call a function without a name an anonymous function. Function return value. The result of function execution is the function return value. return can return the results in the function to a call outside the function. When the return statement is used, the function stops execution, return the specified value and execute it from the called place. The function call will be replaced by the return value. The same function should return only one type of value. When you only want to exit the function, you can also use return. The return value is optional. For example, in the following code: if a is greater than B, exit the function and do not calculate the sum of a and B.

function myFunction(a, b){     if (a > b){         return;     }     x = a+b; }

(9) function parameter passing: You can pass values to a function when calling a function. These values are called parameters. These parameters can be used in a function and can pass any number of parameters, separated by commas (,), for example, function myFunction (x, y) {return x * y;}. input the value myFunction (3, 4) During the call ), returns the result of x multiplication y. Simply put, a parameter is a placeholder, that is, occupying the position first and then using it later. The passed value must appear in the same order as the parameter. The first value is the value given by the first passed parameter, and so on. The function is flexible. Different values can be passed to call the function. Function parameters can be divided into explicit parameters and hidden parameters (arguments ). The explicit passing parameter of a function, also called a fixed parameter, is the parameter listed when the function is declared and defined. Hidden parameters are also called variable parameters or indefinite parameters. The arguments object is a built-in JS object that contains an array of parameters for function calls, through this, you can easily find the value of the last parameter, or calculate the sum of all parameters. When a part of a function cannot be determined, you can use the function to transmit parameters. For example, click the button to change the DIV style:

  

Script function setWid (name, value) {// function parameter var x = document. getElementById ('p1'); x. style [name] = value;} script
1 // sum of parameters: 2 script 3 function sumArr () {4 var result = 0; 5 for (var I = 0; I <arguments. length; I ++) {6 result + = arguments [I]; 7} 8 return result; 9} 10 alert (sumArr (3,5, 2,12, 8,51, 99 )); // sum: 18011 script

(10) objects: in real life, a person can be regarded as an object. Objects have attributes such as gender, height, age, and nationality. The methods include: steps, runs, and jumps. All people have these attributes, but each person has different attributes. All people have these methods, but their execution time is different. In JS, objects are data with attributes and Methods. Everything in JS is objects: strings, dates, arrays, numbers, and so on. It can be said that everything in JS is an object. attributes are values related to objects, and methods are actions that can be executed on objects. Simply put, an object is only a special data type with attributes and methods. In JS, the object is data (variable) and has attributes and Methods. When declaring a variable, var txt = "hello"; actually, a string object has been created, this object has the length attribute. A String object also has many built-in methods. For example, charAt () can obtain a character and return a character of a string. It can be said that JS objects are containers of variables. However, JS objects are usually considered as containers of key-value pairs. Key-value pairs are written as name: value, and keys and values are separated by colons, key-value pairs are also called object attributes, so JS objects are the containers of attribute variables. JS supports custom objects and can be created using the new keyword.

6. JS Data Types

JS data types can be divided into two types: Basic Data Types and composite data types. The basic data types include String, Number, and Boolean), Null, Undefined ). A composite data type is an Object. An Object is essentially a group of unordered name-value pairs. Strictly speaking, it is divided into three types: Object and Array), function ).

(1) string: A string is a variable that stores characters. For example, var a = 'xiaoming '; a string can be any text in quotation marks, and can be single or double quotation marks.

(2) number: a number is a variable used to store numbers. It can be an integer or a decimal number. For example, var a1 = 314; var a2 = 3.14 ;.

(3) Boolean: The boolean values are "true" and "false". boolean values are often used in conditional testing.

True true: a non-zero number, a non-empty string, or a non-empty object

What is false? Zero number, empty string, empty object (null), undefined

(4) Null: null is a special type with only one value. It indicates an empty object reference and can be used to clear variables.

(5), Undefined: indicates the definition, there are two cases: 1: Really not defined. 2. Although defined, no value is assigned.

(6) Object: The Object is included in braces. Within the brackets, the object attributes are defined in the form of name and value Pair {name: value. Attributes are separated by commas (,), including all types except numbers, strings, and boolean values. For example, var person = {name: "James", sex: "male", id: 5566}; in this example, the object (person) has three attributes: name, sex, id.

(7) Array: Use a separate variable name to store a series of values. Create an Array Using var arr = new Array ();. Then, you can add a value for the Array: arr [0] = 1; arr [1] = 2; arr [2] = 3;, the subscript of the array is based on zero, so it starts from 0. In JS, The new Keyword is often avoided, so the array is created in the form of var arr = [1, 2, 3.

(8) function: a function is actually a method to process data. JS regards a function as a data type and can assign values and transmit values like other data types, this brings great flexibility to programming.

Variable type: the variable itself has no type. It depends on the Data Type stored in it and the type of the stored variable. When declaring a new variable, you can use new to declare its type. For example, var userName = new String; var x = new Number; var y = new Boolean; var cars = new Array; var person = new Object ;. JS variables are all objects. When a variable is declared, a new object is created.

Typeof OPERATOR: the typeof operator is used to detect the Data Type of a variable and return a string. String, number, and boolean values are returned. Use typeof to detect null and return the object. In JS, null indicates nothing, but it is an object. Undefined is a variable without a value assignment, so typeof a variable without a value will return undefined. If typeof is an object, the system returns the object. Arrays in JS are special types of objects, so they also return objects. The function returns the function.

The difference between undefined and null: typeof undefined, return undefined. Typeof null, returns the object. (Null = undefined), returns false, (null = undefined), returns true.

7. JS Operators

(1) arithmetic operators:

In addition to common addition and subtraction multiplier, JS also has some other operators:

Modulo operator: %. The common understanding of Modulo is to take the remainder, for example, 5% 2. The value is 1, 5, Division 2, and the quotient is 2 and more than 1.

Auto-increment operator: ++. The auto-increment operation is divided into two types: Assignment first and assignment first, and assignment second. Instance: assume a = 2

Value assignment before calculation: var B = a ++; Calculation Result: B = 2, a = 3 Resolution: B = a, a = a + 1.

First computation and then assign a value: var B = + a; Calculation Result: B = 3, a = 3 Resolution: a = a + 1, B =.

Through the example above, we can see that the assignment is performed first. In essence, a is assigned to B first, and then 1 is added. Value assignment is performed first. In essence, 1 is added first, and then the value is assigned to B.

Their similarities are auto-increment 1, a = a + 1, which are all calculated as an overall expression (a ++) (++ ), although their values all increase by 1, (a ++) takes the value before a's auto increment, and (++ a) takes the value after a's auto increment.

Auto-subtraction OPERATOR: --. The auto-subtraction operator is the same as the auto-increment operator, that is, each time the auto-subtraction operator is 1. There are also two cases: instance: assume a = 2

First assign value and then calculate: var B = a --; Calculation Result: B = 2, a = 1 Resolution: B = a, a = A-1.

First calculation and then assign value: var B = -- a; calculation result: a = 1, B = 1 resolution: a = A-1, B =.

+ Operators can be used to connect string variables. To connect multiple strings, you can use the + operator.

If you add a string and a number, a string is obtained. For example, var str = 'hello' + 2; Return Value: hello2

(2) assignment operator:

The value assignment operator is used to assign values to variables. There are the following types: = + =-= * =/= % =

Instance: assume a = 10 B = 5

=: A = B result: 5

+ =: A + = B, equivalent to: a = a + B result: 15

-=: A-= B, equivalent to: a = a-B result: 5

* =: A * = B, equivalent to: a = a * B result: 50

/=: A/= B, equivalent to: a = a/B result: 2

% =: A % B, equivalent to: a = a/B result: 0 (the modulus operation is the remainder)

(3) Comparison operators:

Comparison operators are used in condition statements to determine the relationship between variables or values. True or false is returned.

Comparison operators include: ====! =! ==><>=<=

Instance: assume a = 2

=: Equal. Note that the equal sign is equal in JS, and an equal sign is assigned a value. Comparison: a = 2, returns true. If a = 1, false is returned.

===: The value and type are equal. Comparison: a = '2', returns false. A = 2, returns true.

! =: Not equal. The opposite is true. Comparison:! = 2, false,! = 1. True is returned.

! ==: It is definitely not equal to, and is opposite to absolute. The values and types are not equal. Comparison:! = '2', returns true,! = 2. false is returned.

>: Greater. Comparison: a> 5. false is returned.

<: Less. Comparison: a <5, returns true.

>=: Greater than or equal. Comparison: a> = 5. false is returned.

<=: Less than or equal. Comparison: a <= 5, returns true.

(4) logical operators:

Logical operators are used to describe the logical relationship between variables or values.

Logical operators include the following types!

&: And. In mathematics, we represent B greater than a and B less than c as: A & B 9 & a <100, assuming a = 50, return: True.

|: Or. When either of the two conditions is met, the logical or operation result is true. Instance: a = 5, B = 10, Judge c =

! : No. It is also called a logical non-operator. It is not reversed. For example, James bought a JS book. Xiao Bai said: It's a turtle book; Xiao Hong said: It's a rhinoceros book. James said: what Tom says is not true. What Xiao Hong says is not false. That's right, Xiao Hong said. James bought a Chinese rhinoceros book. Instance: a = 10 B = 5, Judge c =! (A> B). The value of c is false.

(5), ternary operators:

A Ternary operator is also called a conditional operator. Its basic form can be expressed by an if judgment statement. It is represented by a ternary OPERATOR :? :.

The so-called ternary operator, as its name implies, requires three operations. The syntax is: condition? Result 1: result 2. The condition is written before the question mark, followed by result 1 and result 2 separated by a colon. If the condition is met, result 1 is returned. Otherwise, result 2 is returned. For example, if you want to go to the concert, you need an admission ticket. If you bring it, you can go in directly. If you don't bring it, please go back. You can use the ternary operator to indicate that you have not brought any admission ticket? Bring in directly: if not, please go back.

You can use the ternary operator to determine the statement where the if clause is used. The code for using the if clause is cumbersome. The code for using the ternary operator is very concise, but for beginners, the ternary operators are not so intuitive. if statements are easier to understand. As learning continues to deepen and understanding, you can use the ternary operators instead of if.

Instance: determines whether a number is an even number or an odd number. Suppose: a = 12

First use the if judgment statement:

Var a = 12; if (a % 2 = 0) {alert ('A is an even number ');} else {alert ('A is an odd number ');}

It can be expressed:

Var a = 12; a % 2 = 0? Alert ('even '): alert ('odd ');

(6) Priority between operators:

From high to low: Arithmetic Operators → comparison operators → logical operators → "=" value assignment symbols

The operation of the same level is performed from left to right. If there are Parentheses, the operation is performed from the inside out of the multilayer brackets.

Instance:

Var numA = 2; var numB = 5; var numC = numA + 40> 10 $ numB * 2 <20; var numD = (numA + 40) /(12-numB) * 10; alert (numC); // return: ture alert (numD); // return: 60

8. JS events

HTML events occur on HTML elements. When Javascript is used on an HTML page, JS can trigger these events. Events can be browser actions or user actions. user actions can be divided into mouse operations and keyboard operations. For example, an event is triggered when the page is loaded. This is a browser action. User Actions include clicking a button to trigger an event, moving and removing the mouse, and clicking a button to submit information.

Below are some common event lists:

The above is a summary of JavaScript learning. [2] JS basics. For more information, see PHP Chinese website (www.php1.cn )!

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.