JavaScript Basics:

Source: Internet
Author: User
Tags arithmetic operators logical operators

I. JavaScript overview

JavaScript is a literal-translation scripting language, which is a dynamic type, a weak type, a prototype-based language, and a built-in support type.

document.write (" to display content on a Web page
alert ("Hello") pop-up window,

Two. JavaScript variables

var ad = 1; Letters start with case-sensitive and cannot be keywords and reserved words

Three. JavaScript data type with typeof () view

Data types in javascript:Undefined, Null, Boolean, number, string, and object.

1. String var carname= ' Head teacher ';
2.Number type var x1=34.00; Use a decimal point to write
3. Boolean type var x=true;
4. Array var cars=new array (); Is the list in Python.
5. Object objects are delimited by curly braces. Inside the parentheses, the properties of the object are defined in the form of name and value pairs (name:value)
var person={firstname: "John", LastName: "Doe", id:5566};
The 6.Undefined type uses VAR to declare a variable, but when it is not initialized, the value of the variable is undefined. var box;
A 7.Null type is a data type that has only one value, that is, a special value of NULL. It represents an empty object reference (pointer), and the typeof operator detects NULL to return an object.

Four. JavaScript operators

1.ECMAScript defines 5 arithmetic operators, subtraction, and remainder . Increment + + and decrement--
The difference between front and back: there is no assignment operation, the front and back are the same. When there is an assignment operation, the predecessor operator is incremented or subtracted and then assigned, and the post operator is then added or subtracted.
2. Comparison operator : less Than (<), greater than (>), less than or equal (<=), greater than or equal (>=), equal (= =) (same size as true 1), unequal (! =), congruent (identity) (= = =) (required size and type are the same ), not identical (!==).
3. Assignment operator : equals (=) plus equals (+ =) minus equals (-=) multiply equals (*=) equals (/=) equals (%=)
4.JavaScript logical operators : Logic and (and):&&, logical OR (OR): | | ,, logical non (not):!
5. Comma operator : You can perform multiple operations in a single statement. var box = +, age =, height = 178;//multiple variable declarations
6. Ternary conditional operator : var box = 5 > 4? ' A ': ' B ';//Yes, 5>4 returns true to assign ' a ' to box, whereas ' B ' is assigned to box.
7. Operator Precedence:

Five. JavaScript Process Control Statements

1. Conditional Branch Statement if () {} else {}

if (conditional expression) {statement;}
else if (conditional expression) {statement;} ...
else {statement;}

2. Multi-branch Statement switch () {Case n: ...}; A switch statement is a multiple-condition judgment used to compare multiple values for equality.

var box = 1;
Switch (box) {//To determine multiple values for box equality
Case 1:
Alert (' one ');
Break break; To prevent a statement from penetrating
Case 2:
Alert (' both ');
Break
Default://equivalent to the else in an if statement, otherwise meaning
Alert (' Error '); }

3.do...while Statement : Run first, then judge the Loop statement. That is, the loop body is run at least once, regardless of whether the condition is satisfied.

var box = 1; If it is 1, execute five times, if it is 10, perform 1 times
Do {alert (box); box++;}
while (box <= 5); Run first, then judge

4. While statement: a loop statement that is first judged and then runs. The loop body can be run after the condition has to be met.

var box = 1; If it is 1, execute five times, if it is 10, do not perform
while (box <= 5)//Judge First, then execute
{Alert (box); box++;}

5. For statement: is also a kind of first judgment, after running the loop statement. However, it has the ability to execute the code before executing the loop before initializing the variable and defining the loop.

for (var box = 1; box <= 5; box++) {alert (box);}

The first step, declare the variable var box = 1;

Step two, Judge Box <=5

Step three, alert (box)

Fourth step, box++

Fifth step, from the second step, until the judgment is false.

6. for...in statement: is a precise iteration statement that can be used to enumerate the properties of an object.

var box = {' name ': ' Head Teacher ', ' age ': +, ' height ': 178}; Create an Object
For (var p in box)
{alert (P);} Enumerate all the properties of an object

The break and continue statements are used to precisely control the execution of code in a loop.

VI: JavaScript functions

1. A function is a code snippet that completes a function, 2. A function is a code snippet that can be executed repeatedly, 3. Functions for easy management and maintenance

function name ([parameter] [parameter] [parameter]) {
Code snippet
return value}

For example:function Peoplenameage (name,age) {

Alert (' Your name: ' +name+ ' your Age: ' +age ');

}

Function Note:
1. The function name does not contain special characters, it is best to follow the camel-style naming method, strictly case-sensitive, if the repetition will overwrite
2. Functions can have parameters or can have no parameters, can have one parameter can also have multiple parameters
3. function returns the value via return, if no default return undefined
4. function does not call do not execute

Seven. JavaScript arrays

1. Create an array using the New keyword, var box = new Array (' Cao Teacher ', ' web ', ' learning God '); Create an array and assign the elements
2. You can omit the new keyword.
3. Create an array using the literal method var box = [' Cao Teacher ', ' web ', ' learning God ']; To create an array containing elements

Use index subscript to read the value of the array,alert (box[2]); Get a third element
Use the Length property to get the array element amount alert (box.length) //Get the number of elements
Box.length = 10; Mandatory number of elements
Box[box.length] = ' js technology '; add an element to an array by length

Eight. JavaScript objects

all things in JavaScript are objects: strings, numbers, arrays, functions ...

1. Create an object using the new operator

Ar people= New Object (); New mode
People.name= ' Head '; Create an attribute field
people.age=18; Create an attribute field

2.new keywords can be omitted

3. Create an object using the literal method

4. Use literal and traditional copying methods

var people ={};
People.name= ' head '; Literal declaration as empty object
people.age=18; Point symbol to attribute copy

6. Two ways to export properties

alert (people.age); Dot notation Output
Alert (People [' age ']); Bracket notation Output, note the quotation marks

7. Creating methods for objects

var people ={

Run:function () {
Return ' Running!!! ‘;}

}
Alert (People.run ()); Calling methods in an object

8. Delete Object properties using Delete

In the actual development process, we generally prefer the literal declaration method.

Nine. JavaScript BOM

There is no formal standard for the browser object model (BOM) Browser object model (Browser object models).

1. The warning box is: alert (' AAA '); When the warning box appears, the user needs to click the OK button to continue the operation. Used to ensure that users can get some information.
2. The confirmation box is used to verify that the user action is accepted.

When the confirmation card pops up, you can click "Confirm" or "Cancel" to determine the user action. Click "Confirm" to return true; Click "Cancel" to confirm that the box returns false.
if (Confirm ("Do you Like me?") "))
{alert (' Like! ‘);}
Else{alert (' Don't like it! ‘);}

3. Hint box: Used to prompt the user to enter a value before entering the page.

When the prompt box appears, the user needs to enter a value and then click the Confirm or Cancel button to continue the manipulation. If the point is confirmed, the return value is the value entered. If the point is canceled, the return value is null.
var name = prompt ("Please enter your name", "");
if (name) {alert ("Welcome You" +name);}

10. JavaScript DOM (Document Object model)

It provides a convenient and simple method and properties for locating nodes so that we can quickly operate on the nodes.

respectively: getElementById (), getElementsByTagName (), Getelementsbyname (), getattribute (), SetAttribute (), and RemoveAttribute ( )。

1.getElementById () method

document.getElementById (' box '); Gets the element node with the ID of box

2.getElementsByTagName () method; Returns an array of objects htmlcollection (NodeList), which holds a list of all nodes of the same element name.

document.getElementsByTagName (' * '); Get all elements
document.getElementsByTagName (' Li '); Gets all the LI elements, returning an array

3.getElementsByName () method; Gets an element of the same name, returning an array of objects htmlcollection (NodeList).

Document.getelementsbyname (' add ')//Get INPUT element

4.getAttribute () method; Gets the value of an attribute in the element.

document.getElementById (' box '). getattribute (' id '); Gets the ID value of the element

5.setAttribute () Method: Sets an attribute and value in an element. It needs to accept two parameters: property name and value. If the property itself already exists, it will be overwritten.

document.getElementById (' box '). SetAttribute (' Align ', ' center '); Setting properties and Values

6.removeAttribute () Method: You can remove HTML attributes.

document.getElementById (' box '). RemoveAttribute (' style '); removing properties from

Eleven. JavaScript events

An event is a series of actions caused by the user who accesses the Web page, and then executes a series of code when the user performs certain actions. For example: The user clicks, then executes the corresponding code as follows:.
In HTML, the event handler function is executed as a property of the JS code:

<input type= "button" value= "buttons" onclick= "alert (' Lee ');"/> is equivalent to:

var input = document.getelementsbytagname (' input ') [0]; Get input Object
Input.onclick = function () {//anonymous function execution
Alert (' Lee '); };

OnClick link, button, form object, image map area when user clicks Object
onblur window, frame, all form objects when focus is moved away from the object
OnDblClick links, buttons, form objects when a user double-clicks an object
OnError script When a syntax error occurs in a script
onfocus window, frame, all form objects when you click the mouse or focus the mouse movement on the window or frame
onkeydown documents, images, links, forms when the key is pressed
onkeypress documents, images, links, forms when the key is pressed and released
onkeyup documents, images, links, forms when keys are released
onmouseout link when the icon moves out of the link
onMouseOver links When you move the mouse over a link
OnReset Click the Reset button of the form to reset the form button
OnResize window when a Form object is selected
Onselect form elements When a form object is selected
onsubmit form when sending form to server

12 . JavaScript Dimension style Operation

If you need to change HTML element style, please use this syntax:

document.getElementById (ID). style. Property name = new Style

var box = document.getElementById (' box '); Get box

Box.style.css.style; Cssstyledeclaration

Box.style.css.style.color; Red

Box.style.css.style.fontSize; 20px

Note : If you encounter a CSS style with a bar example: Font-size needs to be rewritten to fontsize, remove the bar and capitalize the first letter

1. Get the size of an element by using the style inline

var box = document.getElementById (' box '); Get element

Box.style.width; 200px, empty

Box.style.height; 200px, empty

2.scrollWidth and ScrollHeight This set of properties can get the element size of the scrolled content.

Box.scrollwidth; 200

Box.scrollwidth; 200

3.offsetWidth and Offsetheight This set of properties returns the actual size of the element, including the border, padding, and scroll bars.

Box.offsetwidth; 200

Box.offsetheight; 200

4.clientLeft and ClientTop This set of properties can get the size of the left and top borders set by the element.

Box.clientleft; Get the length of the left border

Box.clienttop; Gets the length of the top border

5.offsetLeft and offsettop This set of properties can get the position of the current element relative to the parent element.

Box.offsetleft; 50

Box.offsettop; 50

ScrollTop and ScrollLeft

6. This set of properties can get the size of the area to which the scrollbar is hidden, or it can be set to navigate to that area.

Box.scrolltop; Get the position above the scrolling content

Box.scrollleft; Get the left position of scrolling content

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