Chapter II JavaScript core syntax

Source: Internet
Author: User
Tags arithmetic operators logical operators naming convention pear uppercase letter

Chapter I avascript core Grammar I. Declaration and assignment of variables

JavaScript is a weakly typed language with no explicit data type, that is, when declaring a variable without specifying a data type, the type of the variable is determined by the value assigned to the variable.

In JavaScript, variables are declared using the keyword VAR, syntax:

var is a valid variable name;

JavaScript has the same variable naming rules as Java naming conventions.

JavaScript is case-sensitive, so variable names with different case sizes represent different variables.

In addition, because JavaScript is a weakly typed language, it is allowed to be used directly without declaring a variable, and the variable is automatically declared by the system. For example: x=88;//does not declare X to be used directly.

Two. Data type 1. Undefined (undefined type)

The undefined type has only one value, which is undefined. When the declared variable is not initialized, the default value of the variable is undefined, for example: Var widtd;

2. Null (NULL type)

A null type has only one value, which is null. means "Nothing", used to detect whether a variable is assigned a value.

The value undefined is actually derived from the value null, so JavaScript defines them as equal. For example:

Alert (null==undefined); True for the returned person

Although the two values are equal, they have different meanings;

Undefined indicates that a variable was declared but not assigned a value;

NULL indicates that a null value is assigned to the variable;

3. Number (numeric type)

The most special type defined in JavaScript is the number type, which represents a 32-bit integer and can represent 64-bit floating-point numbers.

Integers can also be represented as octal or hexadecimal, the octal first digit must be 0, followed by (0~8), hexadecimal hand number must be 0, followed by (0~9) (a~f).

Another special value, Nan (not a number), represents a non-digit, which is the type of #, for example:

Typeof (NaN); Return bit number

4. String (character type)

In JavaScript, a character is a set of text enclosed in quotation marks (single or double quotes).

Unlike Java, JavaScript does not differentiate between "character" or "string", so var a= "A" is also a string type.

Like Java, string is also an object in JavaScript, and it has a length property that represents the lengths of the strings, including spaces, and so on.

Common methods for String objects

Method

Describe

IndexOf (Str,index)

Finds a specified string where str first appears in a string

CharAt (Index)

Returns the character of index at the specified position

toLowerCase ()

Convert a string to lowercase

toUpperCase ()

Convert a string to uppercase

Substring (INDEX1,INDEX2)

Returns the string between index index1 and Index2, and includes the corresponding character of the index index1, excluding index2 corresponding character

Split (str)

Splits a string into a string array in str, str= "" is split into a single character

5. Boolean (Boolean type)

Boolean data is known as Boolean data or logical data, and the Boolean type is one of the commonly used types in ECMAScript, with only two values: True and False

6. typeof

ECMAScript provides the typeof operator to determine exactly what data type a value or variable belongs to.

Syntax: typeof (variable or value);

The values it returns are as follows:

1) undefined

2) Number

3) String

4) Boolean

5) Object: If the variable is a null type, or if the variable is a reference type, such as an object, an array, a function, returns an object

Three. Arrays

Like Java, arrays in JavaScript need to be created, assigned, accessed, and treated with array elements through some of the array's methods or properties.

    1. Create an array

Syntax: var array name =new array (size);

For example: Var fruit=new array (5); indicates that an array of 5 elements is created with a name called fruit.

    1. Assigning a value to an array element

1) var fruit=new Array ("Apple", "pear", "orange", "peach");

2) var fruit=new Array (4);

fruit[0]= "Apple";

fruit[1]= "Pear";

Fruit[2]= "Orange";

fruit[3]= "Peach";

3) var fruit=["Apple", "pear", "orange", "Peach"];

    1. accessing arrays

You can access an array's representation by directly accessing the array's elements via the array's name + subscript: array name [subscript]. For example, Fruit[0] identifies the first element in the array, fruit the array name, and 0 indicates the subscript.

    1. Properties and methods commonly used in arrays

Category

Name

Describe

Property

Length

Sets or returns the number of elements in the array, for shaping

Method

Join ()

Put all the elements of an array into a string, separated by a delimiter

Sort ()

Object array Sorting

Push ()

Adds one or more elements to the bottom of the array and returns the new length

1) Length

If the size value of the array is specified when the array is created, the length value of the array is the specified size value, regardless of whether the actual data is stored in the array. For example, Var fruit=new Array (4); then fruit.length=4.

2) Join (delimiter)

Cases:

var fruit= "Apple,orange,peach,banana";//Create a string

var arrlist=fruit.split (",");//define an array to receive strings fruit with "," split elements

var str=arrlist.join ("-");//Use the "-" symbol to concatenate elements of an array into a string

Results: Apple–orange–peach-banana

Four. Operational symbols

Category

Operation symbols

Arithmetic operators

+ 、-、 *,/,%, + + 、--

Comparison operators

>, <, >=, <=, = =,! =, = =,!==

logical operators

&&, | |,!

Assignment operators

=, + =,-=

= = = = Identity, requires equal value type and value, = = requires equal values

!=== means not identical, take counter = = =

Five. Logical control statements

In JavaScript, logical control statements are used in the order of execution of control programs, as in Java, and are divided into two categories:

    1. Conditional structure

1) If structure

2) Switch structure

    1. Loop structure

1) for Loop

2) While loop

3) Do-while Cycle

4) For-in Cycle

Grammar:

For (variable in object) {

}

Examples: var fruit=["Apple", "orange", "Peach", "Bannaa"];

for (var i in fruit) {

document.write (fruit[i]+ "<br/>");

}

5) Interrupt Loop

You can exit the entire program immediately.

Continue; exit the current loop only, judging the next loop based on the condition

Six. Notes

When line comment://

Multiline Comment:/* Comment content */

Seven. Keywords and reserved words

Keywords (first letter all lowercase)

Break

Case

Catch

Continue

Default

Delete

Do

Else

Finally

For

Function

If

Inch

instanceof

New

Return

Switch

This

Throw

Try

Typeof

Var

Void

While

With

Reserved words (first letter all lowercase)

Abstract

Boolean

Byte

Char

Class

Const

Debugger

Double

Enum

Export

Extents

Final

Float

Goto

Implements

Import

Int

Interface

Long

Native

Package

Private

Protected

Public

Short

Static

Super

Synchronized

Throws

Transient

Volatile

Eight. Common input/output
    1. Alert () Warning

Syntax: alert ("hint message");

Creates a special dialog box with a string and OK button

    1. Prompt () Tip

Syntax: prompt ("hint info", "input box default information or empty input box");

Prompt () method The first parameter value is displayed on the dialog box, usually a hint, the second input box appears in the User input text box, there are "OK" and "Cancel" two buttons, "Cancel" is returned as null, "OK" returns a string type data.

Nine. Syntax conventions
    1. Case-Sensitivity

1) JavaScript keywords, such as for and if, are always lowercase

2) built-in objects, such as math and date, start with an uppercase letter

3) The name of the object is usually lowercase, followed by the camel nomenclature.

    1. Names of variables, objects, and functions

The same as the Java naming convention, "under the word beauty ..."

    1. Semicolon

JavaScript allows developers to decide for themselves whether to end a line of code with a semicolon, and if there is no semicolon, JavaScript considers the end of the line code as the end of the statement.

For code specifications, it is not recommended to end with a semicolon.

10. Commissioning

Open the Chrome browser and press F12 to enter the debug:

>1:elements: Used to view and edit HTML and CSS elements in the current page.

>2:console: Used to display debug information that is output in a script, or to run a test script.

>3:sources: The source file used to view and debug scripts loaded by the current page.

>4:network: Used to view the details of an HTTP request, such as a request, response, and return content.

>5:timeline: Used to view information such as the execution time of a script, page element rendering time, and so on.

>6:profiles: Used to view information such as CPU execution time and memory consumption.

>7:resource: Used to view the resource files requested by the current page, such as the html,css style.

>8:audits: For optimizing front-end pages, accelerating page loading speed, etc.

Second, the output of variable values through the alert () method can also be debugged.

11. Common system functions
    1. parseint ()

The parseint () function can parse a string and return an integer. If the first character is not a numeric type, Nan is returned, indicating that it is not an array type, and if a non-numeric character is encountered in the middle, the subsequent character is omitted and the preceding value is returned.

    1. Parsefloat ()

The parsefloat () function resolves a string and returns a floating-point number. method is similar to parseint (). If the first character is not a numeric type, Nan is returned, indicating that it is not an array type, and if a non-numeric character is encountered in the middle, the subsequent character is omitted and the preceding value is returned.

Example: Var a=parsefloat (36s22.0);//return value 36.0

    1. IsNaN ()

The IsNaN () function is used to check if its argument is not a number, and if it is not a number returns true if the number returns flase.

Example: Var Flag=isnan ("12.5s"); Returns true, which distinguishes the conversion from the parseint () and Parsrfloat () functions, and the IsNaN () function does not omit the following letters.

12. Custom functions 1. Defining functions

In JavaScript, a custom function consists of a keyword function, a function name, a set of parameters, and the pending JavaScript statements in parentheses, with syntax:

Function name (parameter one, parameter two ...) ){

JavaScript statements;

[Return value]

function is a keyword that defines functions and must have.

2. Calling functions

To execute a function, you must call this function, and when the function is called, you must specify the function name and its subsequent arguments (the parameter function). The invocation of a function is typically used in conjunction with an element's event.

Grammar:

Time name = "function name ([parameter])";

13. Scope of variables

As with variables in Java, in JavaScript, depending on the scope of the variable, it can be divided into global variables and local variables.

A global variable is a variable declared in a script outside of all functions.

A local variable is a variable declared within a function.

14. Events

Name

Description

OnLoad

A page or an image is finished loading

Onlick

Mouse click an object

onmouseover

Move the mouse over an element

OnKeyDown

One of the keyboard keys is pressed

OnChange

The contents of the domain are changed

Cases:

<! DOCTYPE html>

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">

<title> Load Events </title>

<script type= "Text/javascript" >

Function message () {

Alert ("Load, please wait ...");

</script>

<body onload= "message ()" >

Welcome to Learning JavaScript.

</body>

Note:

The OnLoad event occurs immediately after the page or image has finished loading.
Grammar
onload= "Somejavascriptcode" parameter description
Somejavascriptcode required. Specifies the JavaScript that is executed when the event occurs.
HTML tags that support the event:
<body>, <frame>, <frameset>,<iframe>, , <link>, <script>
JavaScript objects that support the event:
Image, layer, window

Chapter II JavaScript core syntax

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.