JavaScript TutorialsJavaScript is the most popular scripting language in the world, and JavaScript is an interpreted programming language that runs in browsers. In the Web world, only JavaScript can drive web pages across platforms, across browsers, and interact with users. The emerging Node.js has introduced JavaScript to the server side, and JavaScript has become a versatile player. JavaScript is really easy to get started with, but its essence is not well known to most developers. Writing high-quality JavaScript code is even more difficult.
Introduction to JavaScriptBecause
Netscape Co.I want to add some dynamic effects to the static HTML page, so call Brendan Eich, who designed the JavaScript language within two weeks. You're right, this guy only took 10 days. Why is it called JavaScript? The reason is that the Java language was booming, so Netscape wanted to use Java's fame to promote it, but in fact JavaScript was a bit like Java in syntax, and the rest was basically nothing.
Quick StartStarting with a double slash until the end of the line is a comment, comments are for people to see, will be ignored by the browser/* in the middle of this is also a comment, will be ignored by the browser * * If you have higher requirements for yourself, you can study the developer tool "source code (Sources)", grasp the breakpoint, single-step execution and other advanced debugging techniques.
Basic SyntaxJavaScript syntax is similar to the Java language, where each statement ends with a statement block with {...}, and can be nested.
JavaScript is best at the end of each statement, ensuring that the results are consistent with expectations. Curly braces {...} Internal statements are best indented to help you organize your code.
data types and variables
The computer can deal with a number, text, graphics, audio, video, Web pages and other data, different data, need to define different data types.
The following types of data are defined in javascript:
1. Number: JavaScript does not differentiate between integers and floating-point numbers, unified by number
2.string: The string is any text enclosed in single quotes ' or double quotes '
3.Boolean value: Boolean value is only true, false two values. &&,| |,! with, or, not separately
4.Array: An array is a set of sequential sets whose values are called elements. An array of JavaScript can include arbitrary data types. [1, 2, 3.14, ' Hello ', NULL, True];,new Array (1, 2, 3);
5.Object: The object of JavaScript is a set of unordered collections consisting of key-values. The key of an object is a string type, and the value can be any data type. Each key is also called an object's property. Gets the properties of an object, we use the object variable. The way the property name is hexadecimal prefix: 0x. For example: 0xff00,0xa5b4c3d2 JavaScript allows you to compare equality operators on arbitrary data types: = = Comparison will convert data type comparisons, = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Including its own only way to Judge Nan is through the equality comparison of floating-point numbers of isNaN () functions: Because the computer cannot accurately represent an infinite loop decimal. To compare the equality of two floating-point numbers, you can only calculate the absolute value of their difference to see if it is less than a threshold Math.Abs (1/3-(1-2/3)) < 0.0000001; The elements of a true array can be accessed by index. Index starting value is 0 declare a variable with the VAR statement, the variable name can also be in Chinese, but please don't get yourself into trouble. Variables of their type are not fixed in the language calledDynamic Language, corresponding to theStatic Language。 Java is a static language variable is not used by the Var declaration, the variable is automatically declared as a global variable, the variable declared using VAR is not a global variable, its scope is limited to the variable declared function body, in order to repair JavaScript this serious design flaw, ECMA has introduced the strict model in subsequent specifications. The strict mode is enabled by writing on the first line of the JavaScript code: ' Use strict ';stringEscape character: ' I\ ' m \ ' ok\ '! That means I ' m ' OK! Hexadecimal \x41 can represent the ASCII character "A", and Unicode characters are available \u### #表示 multi-line strings:Inverted QuotesIndicates that the keyboard is under ESC. Something like ' ... ' in Python. Template string: Concatenate multiple strings and connect with the + sign. ES6 automatically replaces the variable in the string with ${var}, at which point the string quotation mark is changed toInverted Quotes。 Similar to Python3 ' {} '. Fromat (Var)
String manipulation: S.length,s[0] strings are immutable, an index of a string is a common method of assigning meaningless javascript strings, calling methods to return a new string: s= ' Hello '; s.touppercase (); S.tolowercase ( ); S.indexof (' W '); s.substring (0,5); s.substring (7); Array
Common methods for JavaScript arrays:
1. Array Length: Arr.length
2. Arr.indexof (Var);
3. Arr.slice (0,3); Arr.slice (3); Arr.slice ();
4. Arr.push (' A ', ' B '); Arr.pop ();
5. Arr.unshift (' A ', ' B '); Arr.shift ();
6. Arr.sort ();
7. Arr.reverse ();
8. Arr.concat ([1, 2, 3]); a python-like lst.extend
9. Arr.join ('-');
The splice () method is to modify the "universal method" of array, which deletes several elements from the specified index, and then adds several elements from that location:
var arr = [' Microsoft ', ' Apple ', ' Yahoo ', ' AOL ', ' Excite ', ' Oracle '];
Delete 3 elements from index 2 and add two additional elements:
Arr.splice (2, 3, ' Google ', ' Facebook ');//return deleted elements [' Yahoo ', ' AOL ', ' Excite ']
arr; [' Microsoft ', ' Apple ', ' Google ', ' Facebook ', ' Oracle ']
Delete only, do not add:
arr.splice (2, 2);//[' Google ', ' Facebook ']
arr;//[' Microsoft ', ' Apple ', ' Oracle ']
//Add only, do not delete:
Arr.splice (2, 0, ' Google ', ' Facebook ');//return [], since no elements have been deleted
arr;//[' Microsoft ', ' Apple ', ' Google ', ' Facebook ', ' Oracle ']
The index of an array assigns a new value directly to the length of the array, which causes the array size to change, and it is not recommended to directly modify the size of the array slice () is the substring () version of the corresponding string () Directly modifies the element position of the current array concat () method returns a new array if the element of the array is not a string, it is automatically converted to a string and then join.
Object
The object of JavaScript is an unordered collection data type that consists of several key-value pairs. Use {...} Represents an object, which is declared in xxx:xxx form, separated by a key value.
Common methods for JavaScript arrays:
1. New Age attribute: Xiaoming.age = 18;
2. Delete Age attribute: Delete xiaoming.age;
3. Judgment attribute exists: ' age ' in xiaoming;
4. Determine whether the property itself has: Xiaoming.hasownproperty (' name '); Property names contain special characters that must be "enclosed, access this property must use [' xxx '] to access the property that does not exist." Instead of an error, the object returning undefined JavaScript is a dynamic type, and you are free to add or remove attributes to an object If in judge an attribute exists, this attribute is not necessarily xiaoming, it may be the conditional judgment of xiaoming inheritance
JavaScript uses if () {...}} else {...} To make conditional judgments that a statement block contains only one statement, you can omit {}, suggesting that you always write {} JavaScript to treat null, undefined, 0, Nan, and empty strings as false, and all other values as true, So the result of the above code condition is true. Loops
For Loop
var x = 0;
var i;
For (I=1 i<=10000; i++) {//semicolon interval
x = x + i;
}
X 50005000
I=1; i<=10000; i++ are the initial conditions, the judgment condition, the increment condition. For loops the most common place is to use the index to traverse the array for loop 3 conditions are can be omitted, if there is no exit cycle of the judgment conditions, you must use the break statement to exit the loop, otherwise it is dead loop A variant of the For loop is for (the Var key in O) loop, which loops through all the properties of an object, because array is also an object, and its index of each element is treated as an object's property, so for ... in loops can directly loop the index of an array
var a = [' A ', ' B ', ' C '];
for (var i in a) {
console.log (i);//' 0 ', ' 1 ', ' 2 '
console.log (a[i]);//' A ', ' B ', ' C '
}
While Loop
While loops have only one judgment condition, the condition is satisfied, the loop is constant, and when the condition is not satisfied, the loop is exited.
var x = 0;
var n =;
while (n > 0) {
x = x + N;
n = n-2;
}
X 2500
Do ... while loop
var n = 0;
do {
n = n + 1;
} while (n < m);
N 100
The do {...} while () loop body executes at least 1 times, while the for and while loop may not be executed once.
map and set data types
Map and set are new data types for ES6 standards
Map
var m = new Map ([[' Michael ',], [' Bob ', M], [' Tracy ',]]; Two-dimensional array initialization Map
m.get (' Michael ');//
var m = new Map ();//Initialize an empty Map
m.set (' Adam ', 67);//Add New key-value
m.set (' Bob ',);
M.has (' Adam '); Presence of key ' Adam ': True
m.get (' Adam ');//
M.delete (' Adam ');//delete key ' Adam '
A map is the structure of a set of key-value pairs, with an extremely fast lookup speed. Put value on a key multiple times, and the value behind will flush out the previous value
Set Set
var s = new Set (); Initializes an empty set
var s2 = new Set ([1, 2, 3]);//array initialization Set
S.add (4);//add Element
S.delete (3);//delete element
A set is similar to a map and is a set of distinct keys and does not store value
iterable
For ... cycle
var a = [' A ', ' B ', ' C '];
var s = new Set ([' A ', ' B ', ' C ']);
var m = new Map ([[1, ' X '], [2, ' Y '], [3, ' Z ']]);
for (var x of a) {//traverse array
console.log (x);
}
for (var x of s) {//Traverse set
console.log (x);
}
for (Var x of M) {//Traverse map
console.log (x[0] + ' = ' + x[1]);
}
What is the difference between the for ... of loop and the for ... in loop?
A: For ... in traversal is actually the object's property name, which will include the new attribute. For.. of loop, it only loops the elements of the collection itself
iterable Built-in foreach method
var a = [' A ', ' B ', ' C '];
var s = new Set ([' A ', ' B ', ' C ']);
var m = new Map ([[1, ' X '], [2, ' Y '], [3, ' Z ']]);
A.foreach (function (element, index, array) {
//element: value to current element
//index: pointing to the current index
//array: Pointing to the Array object itself C19/>console.log (element + ', index = ' + index];
});
The For ... of loop is the new syntax introduced by ES6. A collection with a iterable type can traverse an array array by means of a new for ... of loop, which is actually an object, and its index of each element is treated as a property iterable the built-in foreach method receives a function, which is automatically recalled each iteration. Set is similar to array, but set has no index, so the first two parameters of the callback function are the element's own map's callback function parameter, in order value, key, and map itself, because JavaScript function calls do not require arguments to be consistent, you can ignore
function
function definitions and calls
function Myabs (x) { //The first way to define functions
//var ABS = functional (x) {//The second way to define functions, anonymous functions, assigning values to the variable myabs
if (typeof x!== ' n Umber ') {//parameter check
throw ' not a number ';
}
if (x >= 0) {return
x;
} else {
return-x
}
}
function to return when the end, and returns the result returned without a return statement, the function will be completed after the result returned, but the result is undefined, like Python return None the second way is to add one at the end of the function body according to the complete syntax, which indicates the end of the assignment statement. JavaScript allows you to pass in any argument without affecting the calling JavaScript keyword arguments, which works only within the function, and always points to the caller of the current function.
All Parameters。 Arguments similar to array but it's not an array. Using arguments, you can get the value of a parameter even if the function does not define any parameters
Rest Parameters
function foo (a, B, ... rest) {
Console.log (' a = ' + a ');
Console.log (' B = ' + B ');
Console.log (rest);
}
Foo (1, 2, 3, 4, 5);
Result:
//A = 1
//b = 2
//Array [3, 4, 5]
foo (1);
Rest parameters can only be written at the end, preceded by ... Identity
variable scope and deconstruction assignmentvar declared variable is actually the scope of the function of the scope of the internal declaration variable is the entire function body, in the function can not be referenced JavaScript function may be nested, internal functions can access the variables defined by the external function, and vice versa the internal function defines a variable with the same name as an external function. Then the internal function's variables will "mask" the variables of the external function to define the variables inside the function, strictly follow the rule "declare all variables first within a function." The most common practice is to use all variables within a var declaration function that are not defined within any function.
Global Scope(Only one). In fact, JavaScript defaults to a Global object window, and global scope variables are actually bound to a window's attribute global variable bound to Windows, to avoid naming conflicts, and are difficult to discover. One way to reduce conflicts is to bind all of your own variables and functions to a global variable
Unique global variable MYAPP:
var MYAPP = {};
Other variables:
myapp.name = ' MYAPP ';
Myapp.version = 1.0;
Other functions:
Myapp.foo = function () {return
' foo ';
};
The variable scope of JavaScript is actually inside the function, and the loop variables defined in the statement block such as for loop are valid inside the function. In order to solve block-level scope, ES6 introduced a new keyword let, with let substitution var can declare a block-level scope variable var and let declaration is variable ES6 standard introduced a new keyword const to define constants, both const and let have block-level scope
Deconstruction Assignment
Starting with ES6, JavaScript introduces the understanding of the construct assignment, which can be assigned to a set of variables at the same time.
var [x, Y, z] = [' Hello ', ' JavaScript ', ' ES6 '];
X, y, Z are assigned the corresponding elements of the array:
console.log (' x = ' + x + ', y = ' + y + ', z = ' + z ');
x = Hello, y = JavaScript, z = ES6 let
[x, [Y, z]] = [' Hello ', [' JavaScript ', ' ES6 ']];
var person = {
name: ' Xiaoming ',
age:20,
Gender: ' Male ',
passport: ' G-12345678 ',
School: ' No.4 Middle School '
};
var {name, age, passport} = person;
Name, age, and passport are assigned the corresponding attributes:
console.log (' name = ' + name + ', age = ' + age + ', Passport = ' + Passport ');
var {name, single=true} = person;
When you use a deconstruction assignment to reduce the amount of code that is assigned to an array element, multiple variables are used [...] Surrounded by the deconstruction of an object, it is also possible to assign values directly to nested object attributes, as long as the corresponding level is guaranteed to be a consistent deconstruction assignment if the corresponding property does not exist, the variable will be assigned to undefined the value can also use the default value, This avoids the problem of nonexistent property return undefined two variables [x, y] = [y, x] If a function receives an object as a parameter, then the object's properties can be directly bound to the variable using deconstruction. For example, the following function can quickly create a Date object
Function Builddate ({year, month, day, hour=0, minute=0, second=0}) {return
new Date [year + '-' + month + '] + day + ' + hour + ': ' + Minute + ': ' + second);
}
Only three attributes of year, month and day are required
builddate ({year:2017, month:1, day:1});
Sun 2017 00:00:00 gmt+0800 (CST)
Method
A function bound to an object is called a method
var xiaoming = {
name: ' Xiaoming ',
birth:1990,
age:function () {
var y = new Date (). getFullYear ();
return y-this.birth;
}
;
Xiaoming.age; function Xiaoming.age ()
xiaoming.age ();//This year's call is 25, next year's call becomes 26.
Inside a method, this is a special variable that always points to the current object, which is the xiaoming variable
function Getage () {
var y = new Date (). getFullYear ();
return y-this.birth;
}
var xiaoming = {
name: ' Xiaoming ',
birth:1990,
age:getage
};
Xiaoming.age (); 25, normal result
getage ();//NaN
Called in the form of an object, such as Xiaoming.age (), which points to the object being invoked, that is, Xiaoming, which is in line with our expectations. If you call a function individually, such as getage (), the function's this points to the global object, which is window
Use Apply to repair Getage () Call
function Getage () {
var y = new Date (). getFullYear ();
return y-this.birth;
}
var xiaoming = {
name: ' Xiaoming ',
birth:1990,
age:getage
};
Xiaoming.age ();
getage.apply (Xiaoming, []);//, this points to xiaoming, the argument is null
apply () A similar method is call (), the only difference is: Apply () to package the parameters into an array and then incoming, call () to the parameters in order. Higher order functions
A function can receive another function as an argument, called a higher-order function map/reduce map () method defined in the JavaScript array, we call the array's map () method, Passing in our own function, we get a new array as the result map () The parameters passed in are POW, that is, the function object itself, which abstracts the operation rules filter sort Closures arrow functions generator Standard Object Object-oriented programming Browser jQuery error handling underscore node.js React Final Summary