Simple learning of JavaScript

Source: Internet
Author: User
Tags list of attributes setinterval

JavaScript introduction
    • JavaScript doesn't have a half-dime relationship with Java.
    • JavaScript consists of three parts: Ecmascript,document Object Model,broswer Object model
    • Two introduction methods, directly after the body <script></script> or file import <script src= "" ></script>
JavaScript Basic Knowledge variables

var imyvalue = 0, smystring = "Gaga"

    • The keyword Var, which represents declaring a local variable, is not global.
    • Case sensitive
    • Naming conventions are roughly the same as the Hungarian type. The previous one is the type behind the hump.

    

Key words

    

Data type

Integer:
10 integers in JavaScript consist of sequences of numbers
What is the exact range of the expression?-9007199254740992 (-253) to 9007199254740992 (253)
Integer out of range, accuracy will be affected
Floating point number:
Using decimal points to record data
Example: 3.4,5.6
Use Index to record data
Example: 4.3e23 = 4.3 x 1023

16 binary and 8 decimal expressions
16 binary data front plus 0x, octal front plus 0
16 binary numbers are made up of 16 characters, such as 0-9,a-f
8 binary number consists of 0-7 and 8 digits
16 binary and 8 binary and 2 binary conversion

String

<script> var str= "\u4f60\u597d\n Welcome to \" JavaScript World \ "";

alert (str);

</script>

Common escape characters \ n: newline \ ': single quote \ ': double quote \ \: Right Dash

Boolean type

There are only two values: TRUE or FALSE. Also equals 1 and 0.

null and undefined
    • The undefined type has only one value, which is undefined. When the variable is undefined or the function has no return value.
    • Null is the same as undefined, except when the object is not found.
    • True when judging null==undefined.
Data type conversions

Some data types are automatically converted during the calculation, without error.

Like what:

Number + String : Number converted to string

Number + Boolean: True converts to 1,false to 0

String + Boolean value : Boolean converted to string true or False

There are some keywords for forced conversions: Parseint,parsefloat,eval.

A nan appears in the process of forcibly converting to int. Indicates that the conversion failed. is a special type.

Nan in comparison, only nan! =nan is true.

typeof to query the data type.

ECMAScript operator
    • Sometimes the Plus + can be used in the concatenation of strings.
    • Minus-sometimes indicates negative numbers.
    • The difference between I and i--is like C. Add the assignment first and then the first assignment.
    • Logical operator: equals (= =), not equal to (! =), greater than (>), less than (<)? greater than or equal to (>=), less than or equal (<=) with (&&), or (| |), non-(!)
ECMAScript relational operators

    

12 varbResult = "Blue""alpha";alert(bResult); //输出 true  

In the example above, the string "Blue" is less than "alpha" because the character code of the letter B is 66, and the character code for the letter A is 97.

Comparing numbers and strings

Another tricky situation occurs when comparing numbers in the form of two strings, such as:

12 varbResult = "25""3";alert(bResult); //输出 "true"

The above code compares the strings "25" and "3". Two operands are all strings, so the comparison is their character code ("2" character code is 50, "3" character code is 51).

However, if one of the operands is a number, the result is interesting:

12 varbResult = "25"< 3;alert(bResult); //输出 "false"

Here, the string "25" will be converted to the number 25, and then compared with the number 3, the results are expected.

Summarize:

12 比较运算符两侧如果一个是数字类型,一个是其他类型,会将其类型转换成数字类型.比较运算符两侧如果都是字符串类型,比较的是最高位的asc码,如果最高位相等,继续取第二位比较.
Boolean operator
var temp=New Object (); // false; [];0; Null Undefined;object (New object ();)    if(temp) {        console.log ("Yuan")    } Else {        Console.log ("Alex")    }

It's all fake!

void ()

A function that does not return a value returns a undefined, and a function that is also void is undefined.

Control statement If statement

If (true) {alert ("executes when True")}else{alert ("executes when false")}

There is also an else if in the middle.

Switch statement

Switch basic format

switch (expression) {

Case value 1: statement 1;break;

Case value 2: statement 2;break;

Case Value 3: statement 3;break;

Default: Statement 4; }

switch is more efficient.

For loop

The For loop is also commonly used for traversal operations.

But note that the loop-out I is the serial number.

for (initialize; condition; increment) {    statement 1;    ...}
While loop

var i=1; while (i<=7) {

document.write (");

document.write ("<br>"); I+ +;}

Exception handling
Try {    // This piece of code runs from top to bottom, where any one of the statements throws an exception the code block ends running }catch  (e) {     // If an exception is thrown in a try code block, the code in the catch code block is executed.     //e is a local variable that points to the error object or other thrown object }finally  {      // the finally code block is always executed, regardless of whether the code in the try is thrown abnormally (even if there is a return statement in the try code block). }
The ECMA object creates an object

var smystrobj = "Gaga";

var smystrobj = new String ("Gaga");

String method
var str2=str1.tolowercase (); convert into lowercase var str3=str1.touppercase (); Convert into uppercase
     var str2=str1.indexof ("L"), index     var str3=str1.lastindexof ("L") from left to right, index displayed right to left
    var str2=str1.match ("World"); Returns an array of "world"     var str3=str1.search ("World"); return index
     var Str2=str1.charat (28); returns     the string var str3=str1.charcodeat (28); Returns the Unicode encoding of a string
     var str2=str1.substr (2,4), 4     var str3=str1.substring (2,4) from 2 intercept, 2 intercept to 4 including tail
     var str2=str1.replace ("CD", "AAA");
     var strarray=str1.split (","); split return array
     var str2=str1.concat ("Efgh"); splicing  or + number
Arrays Array

Similar to tuple (), supports index [], slice slice ().

New Array (Element0, Element1, ..., ELEMENTN)

Several common methods

Push (value), into the stack operation.

Pop (); Out stack operation.

Unshift (); The first end into the stack.

Shift (); The first end of the stack.

Reserve (); reverse sort.

Sort ();

Date Object

var nowd1=new Date ();

Alert (nowd1.tolocalestring ());

Gets the date and time getdate () gets the                 day getday ()                 Gets the week getmonth ()               Gets the month (0-11) getfullyear ()            Gets the full year getyear (                Gets the 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)
RegExp Object

Define a Re object and rule.

var reg1 = new RegExp ("^[a-za-z][a-za-z0-9_]{5,11}$", "G");

Reg1.test ("Df14"); The return value is true or false.

"Hello World". Match (/e/g); To find the E rule, G is the keyword.

Math Object

Math is a built-in object. Call:

Math.random (10); generates a random number within 10.

Math.Round (); rounding.

Other: Abs,exp,min,max, etc.

Function object
Function name (parameter) {
? function body;
return value;
}
Another:
var function name = new function ("Parameter 1", "Parameter N", "Function_body");
Anonymous functions:

(function ($) {

var num=13;

$.fn.extend ({

Print:function () {

Console.log ($ (this). html ())});

}

) (jQuery); direct-running anonymous function, in which the middle is its own extension function. FN is the Gem label extension. No FN is an extension of $.

Scope

The scope of JS is consistent with the PY, in curly braces {} is the code block has its own scope.

It is important to note that the JS interpreter creates a scope chain when the JS file is loaded.

BOM Object

BOM Browser object model, so that JS has the ability to chat with the browser.

Window object

Window objects are supported by all browsers.

Conceptually speaking. An HTML document corresponds to a Window object.

Functionally speaking: Controls the browser window.

Use: The Window object does not need to create objects, directly to use.

Some methods:

Alert ()            displays a warning box with a message and a confirmation button. Confirm ()          displays a dialog box with a message along with a confirmation button and a Cancel button. Prompt ()           displays a dialog box to prompt the user for input. Open ()             opens a new browser window or looks for a named window. Close ()            closes the browser window. SetInterval ()      invokes a function or evaluates an expression by the specified period (in milliseconds). Clearinterval ()    cancels the timeout set by SetInterval (). SetTimeout ()       invokes a function or evaluates an expression after the specified number of milliseconds. Cleartimeout ()     cancels the timeout set by the SetTimeout () method. ScrollTo ()         scrolls the content to the specified coordinates.
View CodeHistory object Location object Dom object DOM node

According to the HTML DOM standard, all the content in the HTML document is node:

    • The entire document is a document node (documents object)
    • Each HTML element is an element node (elements object)
    • Text within an HTML element is a text node (the text object)
    • Each HTML attribute is an attribute node (attribute object)
    • Note is a comment node (Comment object)

The DOM tree is drawn to show the relationships between the objects in the document and to navigate the objects.

Node (self) Properties:

    • Attributes-node (element) attribute node
    • nodetype– node type
    • nodevalue– node Value
    • nodename– node Name
    • InnerHTML-Text value of the node (element)

Navigation Properties:

    • ParentNode-parent node (element) (recommended)
    • firstchild– the first child element under a node
    • The last child element under the lastchild– node
    • ChildNodes-Child nodes of nodes (elements)
DOM Events

One of the new features of HTML 4.0 is the ability to enable HTML events to trigger actions in the browser, such as when a user clicks on an HTML element and launches a JavaScript. The following is a list of attributes that can be inserted into an HTML tag to define an event action.

OnClick an        event handle that is invoked when a user taps an object. OnDblClick an     event handle that is called when the user double-clicks an object. The onfocus        element gets the focus.      //Exercise: The input box onblur         element loses focus.       scenario: For form validation, when a user leaves an input box, the Representative has already entered it and we can verify it.       the contents of the onchange domain are changed.      scenario: Typically used for form elements, which are triggered when the element content is changed. (three-level linkage) onkeydown      a keyboard key is pressed.          Application Scenario: When the user presses the ENTER key in the last input box, the form submits. onkeypress     a keyboard key is pressed and released. onkeyup        a keyboard key is released. OnLoad         a page or an image to finish loading. onmousedown    the mouse button is pressed. OnMouseMove    Mouse is moved. onmouseout     the mouse to move away from an element. onmouseover    mouse moves over an element. Onselect      text is selected. OnSubmit      confirm button is clicked.

Two ways to add events:

<div onclick= "alert (123)" > Point me </div><p id= "abc" > Try!</p><script>    var Ele=document.getelementbyid ("abc");    Ele.onclick=function() {        alert ("HI");    }; </script>
View Code

OnLoad

Run as soon as a label has finished loading. This puts the JS code on the label.

<! DOCTYPE html>
Modify HTML
    • Change HTML Content

The simplest way to change the content of an element is to use InnerHTML, InnerText.

    • Change CSS Style
12 <p id="p2">Hello world!</p>document.getElementById("p2").style.color="blue";<br>                             .style.fontSize=48px
    • Changing HTML Properties

Elementnode.setattribute (Name,value)

Elementnode.getattribute (name) <-------------->elementnode.value (DHTML)

    • Create a new HTML element

createelement (name)

    • Delete an existing HTML element

Elementnode.removechild (node)

    • About the class operation

Elementnode.classname

ElementNode.classList.add

ElementNode.classList.remove

    

    

  

Simple learning of JavaScript

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.