JavaScript for the front-end base

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

JavaScript Overview of JavaScript history
    • 1992 Nombas developed the embedded scripting language for C-minus-minus (c--), which was originally bound to Cenvi software, and renamed it Scriptease (the language that the client executes).
    • Netscape (Netscape) received Nombas's philosophy, (Brendan Eich) developed a set of Netscape scripting languages in its Navigator livescript 2.0 product. Sun and Netscape were done together, and then renamed JavaScript.
    • Microsoft then emulated a JavaScript clone called JScript in its IE3.0 product.
    • To unify the three, the ECMA ( European Computer Manufacturing Association) defines the ECMA-262 specification. The International Organization for Standardization (ISO/IEC) also adopted ECMAScript as the standard (iso/iec-16262). Since then, Web browsers have struggled (albeit with varying degrees of success and failure) to ECMAScript as the basis for JAVASCRIPT implementations.
    • ECMA-262 is the official name of the JavaScript standard.
ECMAScript
Year Name Describe
1997 ECMAScript 1 First version
1998 ECMAScript 2 Version change
1999 ECMAScript 3

To add a regular expression

Add Try/catch

ECMAScript 4 Not published
2009 ECMAScript 5

Add "strict mode" strict modes

Add JSON support

2011 ECMAScript 5.1 Version change
2015 ECMAScript 6 adding classes and modules
2016 ECMAScript 7

Increase the exponential operator (* *)

Increase Array.prototype.includes

Note: ES6 means ECMAScript 6.

Although ECMAScript is an important standard, it is not the only part of JavaScript, and certainly not the only one that is standardized. In fact, a complete JavaScript implementation is made up of the following 3 different parts:

    • Core (ECMAScript)
    • Document Object Model (DOM) Documents object models (consolidated js,css,html)
    • Browser object models (BOM) Broswer object Model (integrated JS and browser)

Simply put, ECMAScript describes the content of the JavaScript language itself.

JavaScript is a scripting language
JavaScript is a lightweight programming language.

JavaScript is a programmatic code that can be inserted into an HTML page.

When JavaScript is inserted into an HTML page, it can be performed by all modern browsers.

JavaScript is easy to learn.

how JavaScript is introducedwrite code inside the script tag
<script>  //write your JS code here </script>
Introduction of additional JS files
<script src= "Myscript.js" ></script>
JavaScript Language SpecificationComments (Comments are the mother of code)
This is a single-line comment/* This is
Multi-line Comment */
Terminator

The statements in JavaScript are terminated with a semicolon (;).

JavaScript Language BasicsVariable Declaration
    1. The variable name of JavaScript can be composed of _, number, letter, $, and cannot begin with a number.
    2. declaring variables using var variable names; The format to declare
var name = "Alex"; var age = 18;

Attention:

Variable names are case-sensitive.

Camel-named rules are recommended.

Reserved words cannot be used as variable names.

reserved word listJavaScript data types

JavaScript has a dynamic type

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

Number Type

JavaScript does not differentiate between integral and floating-point types, there is only one numeric type.

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.

Common methods:

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

String

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

Common methods:

Method Description
. length return length
. Trim () Remove whitespace
. Trimleft () Remove the left margin
. TrimRight () Remove the blank on the right
. CharAt (N) Returns the nth character
. concat (value, ...) Stitching
. indexOf (substring, start) Sub-sequence position
. substring (from, to) Get sub-sequences by index
. Slice (start, end) Slice
. toLowerCase () Lowercase
. toUpperCase () Capital
. Split (delimiter, limit) Segmentation

Splicing strings generally use "+"

the difference between slice and substringBoolean type

The difference between python,true and false is lowercase.

var a = True;var B = false;

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

Array

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

Attention:

the question about sort

The elements in the array can be traversed in the following ways:

var a = [Ten, A, 40];for (Var i=0;i<a.length;i++) {  console.log (i);}
null and undefined
    • Null indicates that the value is empty and is generally used when a variable needs to be specified or emptied, such as name=null;
    • Undefined indicates that when a variable is declared but not initialized, the default value of the variable is undefined. There is also the undefined that is returned when the function has no definite return value.

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.

Still don't understand, right!

Type query
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:

    • Undefined-If the variable is of type undefined
    • Boolean-If the variable is of type Boolean
    • Number-If the variable is of type number
    • String-If the variable is of type string
    • Object-If the variable is a reference type or a Null type

Operator arithmetic operators
+ - * / % ++ --
comparison Operators
> >= < <= = = = = = = =!==

Attention:

1 = = "1"  //true1 = = = "1"  //False
logical Operators
&& | | !
Assignment Operators
= += -= *= /=
Process ControlIf-else
var a = 10;if (a > 5) {  Console.log ("Yes");} else {  Console.log ("No");}
If-else If-else
var a = 10;if (a > 5) {  Console.log ("a > 5");} else if (a < 5) {  Console.log ("A < 5");} else {  Console.log ("a = 5");}
Switch
var day = new Date (). GetDay (), switch (day) {case  0:  console.log ("Sunday");  break;  Case 1:  console.log ("Monday");  Break;default:  console.log ("...")}

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

For
for (Var i=0;i<10;i++) {  console.log (i);}
While
var i = 0;while (i <) {  console.log (i);  i++;}
Ternary operations
var a = 1;var b = 2;var c = a > B? A:b
function 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);
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, find the outer function to find it, and find the outermost layer gradually.

A few examples:

1.

var city = "Beijing", function f () {  var city = "Shanghai";  function inner () {    var city = "ShenZhen";    Console.log (city);  }  Inner ();} f ();  What is the output?

2.

var city = "Beijing", function Bar () {  console.log (city);} function f () {  var city = "Shanghai";  return Bar;} var ret = f (); ret ();  What is the print result?

3. Closures

var city = "Beijing", function f () {    var city = "Shanghai";    function inner () {        console.log (city);    }    return inner;} var ret = f (); ret ();
Built-in objects and methods

All things in JavaScript are objects: strings, numbers, arrays, dates, and so on. In JavaScript, objects are data that owns properties and methods.

We have learned about the basic data types, the number object in JavaScript, the string object, the array object, and so on.

Custom Objects

Similar to (in some respects) a dictionary data type in Python

var a = {"name": "Alex", "Age": 18};console.log (A.name); Console.log (a["age"]);

Iterate through the contents of the object:

var a = {"name": "Alex", "Age": 18};for (var i in a) {  console.log (i, A[i]);}

Things are not that simple ...

To create an object:

var person=new Object ();  Create a Person object person.name= "Alex";  The Name property of the Person object person.age=18;  The age property of the person object

Extended:

JavaScript Object-oriented inheritanceDate Object

Create a Date Object

Method 1: Do not specify the parameter var d1 = new Date (); Console.log (d1.tolocalestring ());//Method 2: The parameter is a date string var D2 = new Date ("2004/3/20 11:12"); Console.log (D2.tolocalestring ()); var d3 = new Date ("04/03/20 11:12"); Console.log (d3.tolocalestring ());// Method 3: The parameter is the number of milliseconds var d3 = new Date (console.log), d3.tolocalestring (), Console.log (D3.toutcstring ());// Method 4: The parameter is month day hour minute second millisecond var d4 = new Date (2004,2,20,11,12,0,300); Console.log (d4.tolocalestring ());  Milliseconds do not show directly

Method of the Date object:

var d = new Date (); GetDate () Get the                 Day//getday ()                 Get the Week//getmonth ()               get the Month (0-11)//getfullyear ()            get the full year//getyear ()                get year/ /gethours () Gets the               hour//getminutes () gets the             minute//getseconds ()             Gets the Seconds//getmilliseconds ()        Gets the milliseconds//gettime ()                Returns the cumulative number of milliseconds (from 1970/1/1 midnight)

Practice:

Write the code to export the current date as "2017-12-27 11:11 Wednesday" format.

Detailed Date object method: Point Me

JSON object
var str1 = ' {' name ': ' Alex ', ' age ': ' obj1 '; var = {' name ': ' Alex ', ' age ': 18};//JSON string converted to object var obj = Json.parse (str1); The object is converted to a JSON string var str = json.stringify (OBJ1);
RegExp Object

JavaScript for the front-end base

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.