JavaScript Language Basics

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

Why do you have javascript?
    • The original purpose of JavaScript

Determine the client's input (previous speed is slow)

    • The meaning of JavaScript now

Page effects (PC-side page effects)
Mobile (mobile web and app)
Asynchronous and server interaction
Server-side development (NODEJS)

    • Show the cool of JavaScript

http://www.codecombat.cn/(game)
http://www.webhek.com/

How the browser works

JavaScript language

JavaScript is the most used scripting language in the world
Scripting languages: Languages that do not require compilation and are executed directly by the edge parsing side
JavaScript is a client-side scripting language

The history of JavaScript

Brendan Eich, who worked at Netscape, began to develop a scripting language called Navigator for the upcoming 1995 release of Netscape LiveScript 2.0, which was intended to be used in browsers and servers (which would have been called Live WIRE) end to use it. Netscape and Sun completed LiveScript implementation in time. Just before Netscape Navigator 2.0 was officially released, Netscape renamed it JavaScript to use Java, the Internet buzzword. Netscape's bets are finally rewarded, and JavaScript has become an essential component of the Internet.

Three pillars
Because JavaScript 1.0 was so successful, Netscape released version 1.1 in Netscape Navigator 3.0. It happened that time, Microsoft decided to enter the browser, released IE 3.0 and a JavaScript version of the clone, called JScript (so named to avoid potential licensing disputes with Netscape). This important step in Microsoft's Web browser landscape is a significant step in the development of the JavaScript language, although it is notorious.
After Microsoft entered, there were 3 different versions of JavaScript that existed: JavaScript in Netscape Navigator 3.0, JScript in IE, and Scriptease in Cenvi. Unlike C and other programming languages, JavaScript does not have a standard to unify its syntax or features, and the different versions of this 3 highlight the problem. As the industry's fears increase, the standardization of the language is clearly imperative.

JavaScript, HTML, CSS

The role of JavaScript, HTML, and CSS
HTML provides content that is displayed on a Web page (structure)
CSS Landscaping page (style)
JavaScript Controls Web page behavior (behavior)
Design principles:
structure, style, Behavior---separation!

The composition of JavaScript

ECMAScript
Syntax specification for JavaScript
Dom
JavaScript API for manipulating elements on Web pages
Bom
JavaScript API for manipulating browser parts of functionality

Introducing JavaScript

HTML page Writing JavaScript

Introducing external JavaScript files

The properties of the script tag

Type
Type= "Text/javascript"
Can omit
Async
async= "Async"
Value can be omitted, immediately asynchronous download external JS, do not affect the other operation of the page, all JS complete execution
Defer
Defer= "Defer"
The value can be omitted, the script is deferred until the document is fully parsed and displayed, and only the external script can use the

Variables for JavaScript

A variable is an identifier that stores data in a computer.
Variables can be assigned at the time of declaration, or they can be assigned later.
For example:
var number = 50;
var name = "Horse household";
Or
var name;
Name = "Zhang San";
You can define multiple variables on a single line
var name,age,sex;

Weak type

JavaScript is a weak type of scripting language
The following two lines of code are legal in JavaScript because JavaScript is a weakly typed language. It is not recommended.
var age = 90;
Age = "Horse household";

Variable naming conventions and specifications

Rules (must be followed)
Consists of letters, numbers, underscores, and $
cannot be a keyword and a reserved word
Case sensitive
Specification (recommended)
The name of the variable should be meaningful
The name of the variable follows the Hump naming method, the first letter lowercase, the first letter of the second word capitalized
Example: UserName

Comments

Single-line Comment
Single-line Comment
Multi-line comments
/* Multiline Comment */
Application of annotations
Annotations are generally used to explain the logic of some complex code, facilitate and later maintenance and development
Annotations are typically used to partition the entire module, making it easier for code to find code and maintain
Annotations are generally used for: modules, functions, complex logic annotations, file annotations, maintenance records, etc.

Goal

Master four types of commonly used data
Number
String
Boolean
Undefined//variable declaration, but not assigned
Null

Data type

The computer has a type when it stores data.
Data types in JavaScript
Simple (Basic, value) data type
Number, String, Boolean
Undefined, Null
Complex (reference) data types (temporarily understood)
Object, Array, date, and so on
View the data type of the current variable
typeof name
typeof (Name)

numeric literal

Literal quantity
A fixed value that lets you understand its meaning literally.
numeric literal
var age = 18; numeric literal, 18 literals

Number Type
Decimal
var num = 9;
When you do arithmetic calculations, the octal and hexadecimal values are eventually converted to decimal values.
Hexadecimal
var num = 0xA;
Number sequence range: 0~9 and A~f
Octal
var num1 = 07; Corresponds to a decimal 7
var num2 = 019; Corresponds to a decimal 19
var num3 = 08; Corresponds to a decimal 8
Number sequence range: 0~7
If the value in the literal value is out of range, then the leading 0 is ignored and the subsequent value is parsed as a decimal value


Number Type

Floating point number
var n = 5e-324;
The highest precision of a floating-point value is 17 decimal places, but it is far less accurate than an integer when doing arithmetic calculations
var result = 0.1 + 0.2; The result is not 0.3, but instead: 0.30000000000000004
Console.log (0.07 * 100);
Never test a particular floating-point value (do not judge whether two floating-point numbers are equal)

Range of values

Due to memory limitations, ECMAScript cannot save all the values in the world.
Minimum value: Number.min_value, this value is: 5e-324
Maximum value: Number.MAX_VALUE, this value is: 1.7976931348623157e+308
Infinity: Infinity
Infinitely small:-infinity

Numerical detection

NaN non-numeric (not a number)
Console.log ("ABC"/18); The result is Nan
Nan is not equal to any value, including Nan itself
IsNaN (): Any value that cannot be converted to a number will cause this function to return true
IsNaN (NaN);//True
IsNaN ("Blue"); True
IsNaN (123); False

String type

string literal
var name = "Zhangsan"; "Zhangsan" literal
strings are enclosed in quotation marks, and the action of single and double quotes is equivalent
For example:
var name = "Zhangsan";
var name = ' Zhangsan ';
var name = ' Zhangsan '; Errors, single and double quotes to appear in pairs
A string is made up of one character, and the number of characters in a string can be used with length
For example: Var name= "ZS"; alert (name.length);//2

Escape character

Want to print "or" What to do?
var str = "Hello \" itcast\ ""; Print output Hello "itcast"
Escape character

The immutable character of a string

The strings in the ECMAScript are immutable, that is, once the strings are created, their values cannot be changed.
To change the string saved by a variable, first destroy the original string, and then populate the variable with another string containing the new value
For example:
var str = "123"; str = str + "ABC";

string concatenation

If there are two string variables, a, B, how do you connect the values of the two variables together?
For example:
var a = "Hello";
var b = "Itcast";
var C = a + B;
Thinking
var a = "100";
var b = 100;
var C = A-B; What was the result?

Boolean type

The Boolean type has two literals: true and false, and case-sensitive!
Although there are only two literals of the Boolean type, values of all types in ECMAScript have values equivalent to these two Boolean values
For example:
var result = Boolean ("a");
Console.log (result); The result is true

var result = Boolean (100);
Console.log (result); The result is true

Convert to Boolean type

Any type can be converted to a Boolean type, typically used behind a Process Control statement
For example:
var message = "Hello";
if (message) {alert (message + "World")};

Undefined type

Undefined this is a special type that indicates that the variable is not assigned, and that only one value of this type is undefined
For example:
VAR message;
Console.log (message); The result is undefined.
Undefined is the literal of the undefined type.
For example:
var message = undefined;
Console.log (message);
typeof message; Get to the "undefined"

Thinking
The result of the following code output?
VAR message;
if (message) {
Alert ("with value");
}else{
Alert ("No value");
}

Goal
Master three types of conversions
Convert to String type
Convert to numeric type
Convert to Boolean type

Convert to String

Three ways to convert into characters
1, almost every value has the ToString () method
For example:
var age = 18;
var agestring = age.tostring ();
Console.log (agestring); Result "18"
var result = true;
var resultstring = result.tostring ();
Console.log (resultstring);//Result "true"
ToString () of numeric type, can carry a parameter, output the corresponding binary value
var num = 10;
Console.log (Num.tostring ()); "10" is 10 binary by default
Console.log (num.tostring (10));//"10"
Console.log (num.tostring (8)); "12"
Console.log (num.tostring (+));//"A"
Console.log (num.tostring (2)); "1010"

Three functions to convert a value to a numeric type: Number (), parseint (), parsefloat ()
Parsefloat () Converts a string to a floating-point number
Parsefloat () and parseint are very similar and differ in
Parsefloat will parse the first one. Encountered a second. Or a non-numeric end
Parsefloat does not support the second parameter, only 10 binary numbers can be parsed
If there is only an integer in the parsed content, parse it into an integer

Convert to Boolean type

Two ways to convert Boolean types
Boolean () function
For example:
var B = Boolean ("123"); return Yes
The Process Control statement implicitly converts the following value to a Boolean type
For example:
VAR message;
if (message) {//will automatically convert message to False
Todo...
}
Value converted to false: false, "", 0 and Nan, null, undefined

Guess the result of the following statement
var B =! " 123 ";

The first logical non-action returns a Boolean value based on whatever operand
The second logical non-operation is to reverse the Boolean value
So we get the Boolean value that really corresponds to this value (binding right-to-left)

Goal
Arithmetic operators
Unary operators
Logical operators (&& | |!)
Comparison operators
Assignment operators
Precedence of Operators

Mathematical operators

+ addition operator
If the operator has one operand as a string, the other operand is converted to a string and then the two strings are spliced
For example:
var str = "abc" + 123; Back to "abc123"
-Subtraction operator
* Multiplication operator
/Division Operator
% modulo (take out) operator
/except 0, return infinity
% remainder, return nan

Unary operators

Operators that can manipulate only one value are called unary operators, and are divided into: pre-and post-type
As the name implies, the predecessor should precede the variable to be manipulated, and the latter should precede the variable to be manipulated
When you perform a pre-increment and decrement operation, the value of the variable is changed before the statement is evaluated.

++
Front + +
var age = 18;
++age; Results 19
Execution process
var age = 1;
Age = age + 1;
Rear-facing + +
var age = 18;
age++; Results 19
The difference between the and the predecessor + + is that the increment operation is performed after the entire statement is evaluated, and there is no difference between the above results.
Practice:
var a = 1; var B = ++a + ++a; Console.log (b);
var a = 1; var B = a++ + ++a; Console.log (b);
var a = 1; var B = a++ + a++; Console.log (b);
var a = 1; var B = ++a + a++; Console.log (b);
--Same as + +

logical operators

&& and
is a short-circuit operation *, that is, if the first operand can determine the result, then the second operand is no longer evaluated
Only two operands are true and the result is true
As long as there is an operand of false, the result is false
|| Or
is a short-circuit operation *, if the first operand evaluates to true, the second operand is not evaluated
has an operand of true and the result is true
has an operand of false and the result is false
! Non -
The logical non-operator first converts its operand to a Boolean value, and then the negation
Only one operand

short-circuit operation :
And
Returns the second operand if the first operand is an object
Returns the second operand if the second operand is an object and the first operand is true
Returns Null (nan/undefined) If one of the operands is null (nan/undefined)
Or
Returns the first operand if the first operand is an object
If the second operand is an object, and the first operand is false, the second operand is returned
If two operands are objects, the first operand is returned
Returns Null (nan/undefined) If all two operands are null (nan/undefined)
Non -

Practice:
Non -
Returns False if the operand is an object
Returns true if the operand is an empty string
Returns False if the operand is a non-empty string
Returns true if the operand is 0
Returns False if the operand is any of a non-0 value
Returns true if the operand is Null,undefined,nan
The above rules can be simplified into
Value converted to false: false, "", 0 and Nan, null, undefined
!!" ABC "What's The result?

Comparison operators

< <= >= >
When comparing strings, the actual comparison is the character encoding value for each character in the corresponding position in the two string.
When comparing values and strings, the strings are converted to numeric values and then numerically compared to another value
If there is a number on one side and a Boolean on the other, first convert the value of the Boolearn type to a number, then compare

= = = equals and is not equal
= = =!== congruent and not congruent
Equality only compares values, and the values and types are compared by congruent
For example:
var result = "55" = = 55; True
var result = "55" = = = 55; False values are equal, type is not equal
var result = 55 = = = 55; True

Assignment operators

= += -= *= /= %=
For example:
var num = 0;
num + = 5;//equals num = num + 5;

Precedence of Operators

Priority from high to bottom
() Highest priority
Unary operator + +--!
Arithmetic Operation Mr. Foo */% after +-
Relational operators > >= < <=
Equality operator = = = = = = = =!==
Logical Operation Mr. Foo && Post | |

Exercise 1
((4 >= 6) | | ("people"! = "Dog")) &&! (((2) = = = 144) && true)
Exercise 2
var num = 10;
if (5 = = Num/2 && (2 + 2 * num). toString () = = = "22") {
Console.log (TRUE);
}

Three basic structures of the program

Sequential structure
Select structure
Loop structure

Judgment statement if

Grammar:
if (condition) {
Statement1
}else if (AAA) {
Statement2
}else{
Statement3
}

Ternary (mesh) operator

Gender in the database is stored in 1 and 0, requires the output of male or female
var sex = 1;
if (sex = = = 1) {
Console.log ("male");
}else{
Console.log ("female");
}
A simplified approach
var sex = 1;
sex = Sex = = = 1? "Male": "Female";
Expression 1? Expression 2: Expression 3

Judgment Statement Switch

Grammar:
switch (expression) {
Case Value:
Statement
Break The break keyword causes the code execution flow to jump out of the switch statement
Case Value:
Statement
Break
Default
Statement
}
Attention:
Break can be omitted, and if omitted, the code will continue to execute the next case
The switch statement uses the congruent operator when comparing values, so no type conversions occur (for example, the string "10" is not equal to the number 10).

Practice:
Determine the day of the week
Convert the percentile into a good medium can be poor

Loop statement for

Grammar
for (initialization; expression; post-loop-expression) statement
Initialization: Initializing an expression
Expression: Controlling expressions
Post-loop-expression: Post-loop expression
All three of them are optional.
Loop 1-100
Execution process
1 Initialize First
2 Judgment of the cycle
3 Function Body Code
4 post-loop-expression
5 starting from the 2nd step, repeat down

Practice:
1 Printing 1 to 100
2 printing of 1 to 100 and
3 to 1-100 and the average
4 for 1-100 all even and, all odd and
5 of the principal 10000 yuan deposited in the bank, the annual interest rate is 3 per thousand, every 1 years, the principal and interest added as the new principal. After 5 years of calculation, what is the amount of the principal obtained?
6 One person wants to know how much a pair of rabbits can breed in a year, right? So he built a fence and locked a pair of rabbits in it. It is known that a pair of rabbits can have a pair of rabbits each month, and a pair of rabbits from the 3rd month after the birth of a pair of rabbits a month. If there is no death in a year, how much can a pair of rabbits breed in a year (12 months)?
The law of the Rabbits is an array of 1,1,2,3,5,8,13,21

2 Printing Squares
3 Printing Right Triangle
1 Printing 9*9 multiplication table

From 1 times to 100;
Calculates the sum of the numbers of all integers between 1-100 that cannot be divisible by 7.
Calculates a number between 1-100 and greater than (or equal to) 2000 for all integers that cannot be divisible by 3.

Break and Continue

Break
Exit the Loop now
Continue
Exits the current loop immediately, but resumes from the top of the loop after exiting the loop

Loop statement while

Grammar
while (expression) statement
Execution order
1. Perform expression first
2. Re-execute the code in the loop body
Practice
Enter an integer arbitrarily to find the number of bits

Loop statement do: While

Grammar
Do {statement} while (expression);
The code in the loop body must be executed at least once
Execution order
1. Execute the statement statement first
2. Execute expression again

Why do you want to learn arrays

Previously learned data types, only one value can be stored
We can use arrays when we want to store multiple values
For example: Store the names of all students in the class

Array

Arrays: An ordered list of data that can hold any type of data, and the size of the array can be dynamically adjusted.
Two ways to create an array
Mode 1, array literal
var arr1 = []; Create an empty array, array literal
var arr2 = [1, 3, 4]; Creates an array of 3 values, with multiple array items separated by commas
var arr3 = ["A", "C"]; Create an array with 2 strings
The constructor of the mode 2,array
var arr4 = new Array (); Create an empty array
var arr5 = new Array (10); Create an array of length 10
var arr6 = new Array ("Black", "white", "red"); Create an array with 3 strings

Use of arrays

Gets the value in the array
var colors = ["Black", "white", "red"];
Console.log (Colors[0]); Gets the value of the first element
colors["1"] = "blue"; Assigns a value to the 2nd element
Console.log (colors);
colors["4"] = "yellow"; Sets the value of the 5th element, when there are 5 elements in the array
Console.log (colors);
Length property, Gets or sets the number of elements in the array
Console.log (colors.length);//Gets the number of elements in the array
Colors.length = 1; Sets the number of elements in an array
Console.log (colors);

Array Exercises

Finding and averaging all the numbers in a set of numbers
Find the maximum and minimum values in a set of numbers, and where
To split a string array with a | or other symbol
Requires 0 items in the array to be removed, and a new array will be created without a value of 0.
Flipping an array
Bubble sort, small to large

Debugging

Past Debugs
Alert
Console.log
Set breakpoints

Function

A function can encapsulate a piece of JavaScript code that is defined only once, but can be executed or invoked any number of times
Programming is the ability to break down requirements into a set of functions and data structures
Definition of a function
Function name (var1, Var2, ..., Varx) {
function body
}
Call to function

function name ();

Several forms of function functions
No parameter no return value
There are no return values for parameters
No parameter has return value
There are parameters with return values
function return value
If return is present in the function body, the following code does not execute
The return value is returned when the return value is not written, or when there is no content followed by return undefined, which is different from other languages

return value of the function

The functions in JavaScript are more wonderful
1. If the function does not show the use of the return statement, then the function has a default return value: undefined
2. If the function uses the return statement, then the value returned after the return is the return value of the function.
3. If the function uses the return statement, but there is no value after return, then the return value of the function is also: undefined
4. After the function uses the return statement, the function stops and exits immediately after executing the return statement, which means that all other code after the return is no longer executed.
5. The recommended practice is either to have the function always return a value or never return a value.
Parameters of the function

Parameters of the function

Formal parameters
function f (A, b) {}//a,b is a formal parameter, placeholder, parameter has no value when defined
Actual parameters
var x= 5,y=6;
f (x, y); X, y arguments, with specific values, will copy x, y to A and B inside the function, the value inside the function is the new value copied, cannot modify the external x, y
Functions in JavaScript compared to other languages (special) Live
In other languages, the number of arguments must be the same as the number of formal parameters, but there is no concept of function signature in JavaScript, the number of arguments and the number of parameters can be unequal

No overloads (Learn)
What is overloading: methods have the same signature (function return value, function name, function argument), and overloads of methods in other languages (C + +, Java, C #).
Overloads with no methods in JavaScript
Function F1 (A, b) {
return a + B;
}
Function F1 (a,b,c) {
Return a + B + C;
}
var result = F1 (5,6); NaN
The F1 of three parameters covers the F1 of the two parameters, and the F1 of the three parameters is called.
Prove that there are no overloads in JavaScript

function two ways of defining

1. Function declaration
function f (A, B) {
return a + B;
}
Console.log (f (5,6));
2. Function expression
Myfun and F equivalents
var myfun = function (A, b) {
return a + B;
}
Console.log (Myfun (6,7));

Scope of the variable

Block-level scopes
In other languages, any statement in a pair of curly braces belongs to a block, and all variables defined in it are invisible outside the code block.
There is no block-level scope in JavaScript
Global variables
Variables defined in script or not part of a function
Local variables
Variables defined inside a function
Other
Inside the function, you can access the variable (scope chain) of the outer scope to which the function belongs.
Variables declared without var are global variables and are not recommended for use.
The variable is destroyed after it exits the scope, the global variable closes the Web page, or the browser destroys


Variable Promotion

Variable Promotion
When defining a variable, the declaration of the variable is promoted to the top of the scope, and the assignment of the variable is not promoted.
function promotion
The JavaScript parser will first advance the function declaration of the current scope to the front of the entire scope

The difference between a function declaration and a function expression
function declaration
There is no problem with code execution here, the JavaScript parser first puts the function declaration of the current scope ahead of the entire scope.
Console.log (f (5,6));
function f (A, B) {
return a + B;
}
function expression
Error: Myfun is not a function
What is this for?
Myfun (6,7);
var myfun = function (A, b) {
return a + B;
}

anonymous functions

anonymous function: No named function
Function: Typically used when binding an event
Grammar
function () {}
Self-calling functions
(function () {alert ("Hello")}) ();

Function exercises
To find the area of a circle
For the maximum of 2 numbers, find the maximum value in 3
Determine if a number is prime
Find factorial
Beg 1!+2!+3!+....+n!
Find the maximum and minimum values in a set of numbers
What is the nth number in the Fibonacci sequence Fibonacci? 1 1 2 3 5 8 13 21 ...
Flips an array, returns a new array
Sort an array, from small to large
Enter a certain day of the year, judging the day is the first of the year?

Recursive

What is recursion?
The method itself is called, and generally there is an end to the commit
Case:
There used to be a temple, an old monk in the temple.
The summation of the number of n is obtained
Enter a number to find the sum of the figures for this number.
Find the nth number of Fibonacci
1 1 2 3 5 8 13 21 ...

A function is a data type
typeof F1

function as a parameter of a method
function as the return value of a method

JavaScript Language 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.