JavaScript (i)

Source: Internet
Author: User
Tags arithmetic operators define function logical operators script tag

First, Introduction

JavaScript is one of the most popular programming languages in the world, and the language is used primarily for HTML and WEB.

JavaScript is a scripting language, a lightweight language, programming code that can insert HTML pages, a browser-executed

Second, the introduction of the way

1. Write code within the script tag line

< Script >  // Write your JS code here </ Script >

2, the introduction of additional JS code

<src= "Myscript.js"></script>

Third, JavaScript statements

A JavaScript statement is a command issued to a browser. The function of a statement is to tell the browser what to do.

Semicolons are often used in JavaScript statements, and the main role of semicolons is:

Semicolons are used to separate JavaScript statements. Usually we add semicolons at the end of each executable statement. Another useful use of semicolons is to write multiple statements in one line. Tip: You may also see cases with no semicolons. In JavaScript, concluding sentences with semicolons are optional.

Sensitive to case:

JavaScript is sensitive to capitalization. When writing JavaScript statements, be aware of whether to turn off the case toggle key. The function getElementById is different from the getElementById. Similarly, variable myvariable and myvariable are different.

Extra spaces are ignored in JavaScript statements

**javascript is a scripting language. The browser executes the script code on a line-by-row basis when reading the code. For traditional programming, all code is compiled before execution.

Iv. JavaScript Language Specification

As programmers know that "annotations are the mother of code," So say a good code, a good project must have comments, comments its main purpose is to improve the readability of the Code

This is a single-line comment/* This is a multiline comment */

V. variables

Variables are containers for storing information

declaring variables

1, javascript variable name can use _, numbers, letters, $ composition, can not start with a number.

2, declare variables using var variable name; The format to declare

Attention:

Variable names are case-sensitive.

Camel-named rules are recommended.

Reserved words cannot be used as variable names.

Add:

ES6 has a new let command for declaring variables. The usage is similar to Var, but the declared variable is valid only within the block of code where the Let command resides.

For example, a For loop counter is good for using the Let command.

For (Let I=0;i<arr. length;i++) {...}

ES6 New Const is used to declare constants. Once declared, its value cannot be changed.

Const PI = 3.1415; Pi//3.1415PI = 3//TypeError: "PI" is read-only
Abstractbooleanbytecharclassconstdebuggerdoubleenumexportextendsfinalfloatgotoimplementsimportintinterfacelongnativepacka Geprivateprotectedpublicshortstaticsupersynchronizedthrowstransientvolatile
reserved word supplement

JavaScript variables are objects. When you declare a variable, a new object is created.

Vi. Types of data

String, numeric, Boolean, object, Null, Undefined

JavaScript has a dynamic type, which means that the same variable can be used as the same type

var x;  At this point x is Undefinedvar x = 1;  At this point x is the number var x = "Alex"  

1. Strings (String)

A string is a variable that stores characters, a string can be any text in quotation marks, and you can use single and double quotation marks

var a = "Hello" var b = "World;var c = a + B; Console.log (c);  Get HelloWorld

Common methods:

tr> /tr>
Method Description
.length return Length
. Trim () remove blank
. Trimleft () remove left blank
. TrimRight () remove blank on right
.charat (n) return nth character
. Concat (value, ...) Stitching
. indexOf (substring, start) sub-sequence location
. Substring (from, to) get sub-sequences by index
. Slice (start, end) Slice
. toLowerCase () lowercase
. toUpperCase () uppercase
. Split (delimiter, limit) split

Stitching string General with + number

String.slice (Start, stop) and string.substring (Start, stop): The same point: if Start equals end, returns an empty string if the stop parameter is omitted, Take to the end of the string if a parameter exceeds the length of a string, this parameter is replaced by the string length substirng () feature: If Start > Stop, start and stop will be swapped if the parameter is negative or not a number, will be replaced by 0 silce () feature: If Start > Stop does not swap both if start is less than 0, then the cut starts at the end of the string with the first number of points of ABS (start) (including the character of that position) if stop is less than 0, The cut ends at the end of the ABS (stop) character from the end of the string, not including the position character.
the difference between slice and substring

A template string was introduced in ES6. The template string, which is an enhanced version of the string, is identified with an inverse quotation mark ('). It can be used as a normal string, or it can be used to define a multiline string, or to embed a variable in a string.

Normal string ' This is a normal string! '//Multiple lines of text ' This is a multiline text '//string in the embedded variable var name = "Q1mi", time = "Today"; ' Hello ${name}, how is you ${time}? '

Attention:

If you need to use anti-quotes in the template string, precede it with a backslash to escape.

Jshint Enable ES6 Syntax support:/* jshint Esversion:6 */

2. Value (number)

There is only one numeric type in JavaScript, with no distinction between integral and floating-point types.

var a = 12.34;var b = 20;var c = 123e5;  12300000var d = 123e-5;  0.00123

There is also a Nan, which indicates that it is not a number.

parseint ("123")  //Return 123parseInt ("ABC")  //Return Nan,nan property is a special value that represents a non-numeric value. This property is used to indicate that a value is not a number. Parsefloat ("123.456")  //Return 123.456

3, Boolean (Boolean)

Boolean has only two properties: True and False

In JavaScript, in the case of Python, it's all lowercase.

var a = True;var B = false;

"" (empty string), 0, null, undefined, Nan are all false.

4. Objects (object)

All things in JavaScript are objects: strings, numbers, arrays, functions ... In addition, JavaScript allows custom objects to be customized.

JavaScript provides multiple built-in objects, such as String, Date, Array, and so on.

Objects are just special data types with properties and methods.

Array

The purpose of an array object is to use a separate variable name to store a series of values. Similar to the list in Python.

var a = [123, "ABC"];console.log (A[1]);  Output "ABC"

Common methods:

Method Description
. length The size of the array
. push (Ele) Trailing append Element
. Pop () Gets the trailing element
. Unshift (Ele) Head Insert Element
. Shift () Removing elements from the head
. Slice (start, end) Slice
. Reverse () Reverse
. Join (SEQ) Concatenate array elements into a string
. concat (Val, ...) Connection array
. Sort () Sort

5, null and undefined

1. Null indicates that the value is empty and is generally used when a variable needs to be specified or emptied, such as name=null;

2. Undefined means that when a variable is declared but not initialized, the default value of the variable is undefined. Also, when the function has no definite return value, the return is also undefined

Null means that the value of the variable is empty, and undefined means that only the variable is declared, but it has not been assigned a value.

ES6 introduces a new primitive data type (Symbol) that represents a unique value. It is the 7th data type of the JavaScript language.

6. Type Inquiry

typeof "ABC"  //"string" typeof null  //"Object" typeof true  //"Boolean" typeof 123//"number"

typeof is a unary operator (like ++,--,! ,-the unary operator), is not a function, nor is it a statement.

Calling the TypeOf operator on a variable or value returns one of the following values:

1, undefined-if the variable is of type undefined

2, Boolean-If the variable is of type Boolean

3, number-if the variable is of type number

4, string-If the variable is of type string

5, Object-If the variable is a reference type or a Null type

Seven, operator

1. Arithmetic operators

+ - * / % ++ --

2. Comparison operators

1.>  2.>=  3.  <  4.<=  5.! =  6. ==   7.=  = =8.! ==

3. Logical operators

1.&&  2.| | 3.!

4. Assignment operators

1.= 2.+= 3.-= 4.*= 5./=

Eight, Process Control

1. Conditional statements

Used to perform different actions based on different conditions

In JavaScript, we can use the following conditional statements:

    • If statement-use this statement to execute code only if the specified condition is true
    • If...else Statement-executes code when the condition is true and executes other code when the condition is false
    • If...else If....else Statement-Use this statement to select one of several code blocks to execute
    • Switch statement-Use this statement to select one of several code blocks to execute

If statement: The statement executes code only if the specified condition is true

If...else statement: Executes code when the condition is true, and executes additional code when the condition is false.

var a = 10;if (a > 5) {  Console.log ("Yes");} else {  Console.log ("No");}

If...else If...else statement: Use the If....else if...else statement to select one of several code blocks to execute

Grammar:

if (condition 1)  {  code executed when condition 1 is true  }else if (condition 2)  {  code executed when condition 2 is true  }else  {  when condition 1 and bar Code to execute when none of the 2 is True  }

Switch statement: Use the switch statement to select one of several code blocks to execute.

Grammar:

Switch (n) {Case 1:  Execute code block 1  break;case 2:  Execute code block 2  break;default:  N code that executes when different from 1 and 2

First, set the expression n (usually a variable). The value of the subsequent expression is compared to the value of each case in the structure. If there is a match, the code block associated with the case is executed. Use break to prevent the code from automatically running down a case.

The case clause in switch usually adds a break statement, or the program continues to execute the statements in the subsequent case.

2. Circular statements

Different types of loops

JavaScript supports different types of loops:

    • For-loop code block for a certain number of times
    • For/in-Looping through the properties of an object
    • While-loops the specified block of code when the specified condition is true
    • Do/while-also loops the specified block of code when the specified condition is true

For loop

Grammar:

for (statement 1; Statement 2; Statement 3)  {  code block executed  }

Statement 1 executes before the Loop (code block) starts

Statement 2 defining conditions for running loops (code blocks)

Statement 3 executes after a loop (code block) has been executed

for (Var i=0;i<i++) {  console.log (i);}

While loop: A while loop executes a block of code when the specified condition is true.

Grammar:

while (condition)  {  code to execute  }
< Ten ) {  console.log (i);  i++;}

3, ternary operation

var a = 1;var b = 2;var c = a > B? A:b

Nine, function

A function is an event-driven or reusable block of code that executes when it is invoked.

1. Function definition

The functions in JavaScript are very similar to those in Python, but the way they are defined is somewhat different.

Normal functions define function F1 () {  console.log ("Hello world!");} function F2 with parameters (A, b) {  console.log (arguments);  Built-in arguments object  console.log (arguments.length);  Console.log (A, b);} function with return value sum (A, b) {  return a + b;} SUM (1, 2);  Call function//anonymous function way var sum = function (A, b) {  return a + b;} SUM (1, 2);//execute functions immediately (function (A, b) {  return a + b;}) (1, 2);

Add:

ES6 allows you to define functions using the arrow (= =).

var f = v = v;//equals var f = function (V) {  return v;}

If the arrow functions do not require arguments or require multiple arguments, use parentheses to represent the parameter part:

var f = () = 5;//equals var f = function () {return 5};var sum = (NUM1, num2) = = Num1 + num2;//equals var sum = function (nu M1, num2) {  return num1 + num2;}

The arguments parameter in the function

function Add (A, b) {  console.log (a+b);  Console.log (Arguments.length)}add (ON)
Output:
3
2

Attention:

A function can only return a value, and if you want to return more than one value, you can only return it in an array or object.

Global variables and local variables for functions

Local Variables :

A variable declared inside a JavaScript function (using VAR) is a local variable, so it can only be accessed inside the function (the scope of the variable is inside the function). As soon as the function is complete, the local variable is deleted.

Global variables:

Variables declared outside of a function are global variables, and all scripts and functions on a Web page can access it.

Variable life cycle:

The lifetime of JavaScript variables begins at the time they are declared.

Local variables are deleted after the function is run.

Global variables are deleted after the page is closed.

Scope:

First find the variable inside the function, then find the outer function, and find the outermost layer gradually.

1.

2.

3. Closed Package

JavaScript (i)

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.