A preliminary study of JS _0702 (i.)

Source: Internet
Author: User
Tags arithmetic operators floor function mathematical functions square root

This article was reproduced from: http://www.cnblogs.com/nhsd/p/3783900.html! Thank you very much, written in a very detailed

JavaScript is a lightweight web-oriented scripting language, often referred to as: JS. Widely used in PC and various mobile devices, often with HTML, CSS together to form a page page. It is also often associated with Java, but in essence they are completely two different programming languages (when I come across this, I believe that someone really thinks so). JavaScript runs, requires an interpreter ("engine"), as part of the browser. The contents of this chapter are:

1, JS references, comments;

2. Variables and data types

3. Operators and expressions

4. Common function objects

5. Type conversion

Before writing: One of the most important tasks in writing a program is debugging, in which all debugging is done in Chrome. To do this: open the browser and press "F12", navigate to the "Control" tab and enter the code in the input field. If you are debugging the JS code in an HTML page, navigate to the Source tab and place the breakpoint where necessary.

A JavaScript reference with note 1.1 references

1) write in

2) The name is named as the suffix ". js" as a <. JS js file is written elsewhere and then used by <script src= "file path" type= "Text/javascript" ></script>. This approach facilitates reuse and unified management, modifying a place where the effects of all the same JS code segments are changed.

3) written in the page file, but outside the

1.2 Notes

There are two ways to annotate JS, and annotations do not run.

1) Single-line comment: var sum = 1 + 1;//after a double slash, and in this line of class, the content is the comment content.

2) Multiline Comment: Also called block comment, it is characterized by the ability to annotate multiple lines at a time, start with/* and end with */, the content between this is the comment section.

1.3 Examples

The following example explains how JavaScript is referenced and commented:

1 <! Doctypehtml> 3 

Note:

1) The <!----, which is also a notation, but it belongs to the HTML.

2) and alert (content), it is a form of a hint JS, save as. html and then open with a browser to see the effect.

3) After each statement is finished, it is divided into an identifier, indicating that the statement ends. Typically, this semicolon can be omitted, but the standard programming specification and in some special occasions (such as writing some functions, plug-ins), it is required that the semicolon cannot be omitted.

Two variables and data type 2.1 variables

Like all other programming languages, JavaScript has variables and variable types that correspond to it. A variable is a container for storing information, and the characteristic of the stored information is called the type of the data. For example: The number is like: 1 2 3, you can perform arithmetic operations. Boolean types such as: true false, can be logically formed and the identity of the logical negation. As a weak type of language, JavaScript variables in the definition of the unified use of Var as the keyword. A complete variable is defined in the following form:

var sum;

var is the identifier keyword for a variable. Sum is the name of this variable. Only one variable is defined here, and you can assign a value to the variable in the form below.

sum = 5;

You can also combine these two statements:

var sum = 5;

When a variable is defined, it is assigned the form of a value, which is called the variable initialization (the variable is assigned the initial values).

If you want to define more than one variable at a time, you can write multiple variables in one line, separated by commas, and write only a variable ID in front of you:

Var max = 10,min = 1;

2.2 Strong type and weak type

Previously, Javascrip was the language of a weakly typed class. If a language can be implicitly and correctly converted to almost all of its variable types, the language can be simply called a weak type (var temp = 123; Console.log (temp + "456");). The strong type that is relative to this is that most of the types are not implicitly convertible (C # int can be converted to double). More prepared and detailed explanations can be Baidu.

2.3 Data types

Although the keyword defined by the JS variable is VAR, the variable will have a different type depending on the value assigned to it. View the data type by "typeof variable name", such as: var t = 1; Console.log (typeof T);

Common types

Boolean type: var isn = true;console.log (typeof isn); It has only true and false values of two.

Number type: var Num = 1;      Console.log (typeof Num); Both integers and decimals are number types in JS.

String type: var str = "123";     Console.log (typeof str); Represents a string, and both single and double quotation marks are correctly represented as string types.

Object type: var Tim = new Date (); Console.log (typeof Tim); An unordered collection of a series of attributes. In addition to dates, arrays and objects are object.

var arr = new Array (Console.log); (typeof arr);

var obj = {' Zs ': ', ' Age ': 14};console.log (typeof obj);

NULL type: A null value, the unique value is NULL, which represents a null reference.

Undefined type: A variable that has no definition or assignment (the JS variable is also followed by "variables defined first, followed by" post-principle).

Nan Type: non-numeric type.

Three-operator and expression

The function of a program is to display and compute. With a variable, there is an operation between the various variables. The main types of operators are: arithmetic operators, assignment operators,

3.1 Arithmetic operators

Extra Var Zhi = 1 + 2; Result: Zhi = 3

Reduction Var zhi = 2–1; Result: Zhi = 1

By Var Zhi = 2 * 2; Result: Zhi = 4

Remove Var zhi = 2/2; Result: Zhi = 1

[Modulo (for redundancy)] Var zhi = 4 3; Result: Zhi = 1

[Self-increment, self-increment re-assignment] Var t = 5; var zhi = t++; Result: T = 5; Zhi = 5[First assigns t to Zhi, then t increases by 1]

[Self-subtraction, self-reduction and re-assignment] Var t = 5; var zhi = t--; Result: T = 4; Zhi = 4[First assigns t to Zhi, then T minus 1]

[Self-increment, first assignment and then self-increment] Var t = 5;var zhi = ++t; Result: T = 5;zhi = 5[t self-increment 1, then T assigns value to Zhi]

[Self-subtraction, first self-subtraction re-assignment] Var t = 5;var zhi =--t;//Result: T = 5;zhi = 5[t Subtract 1 First, then assign T to Zhi]

3.2 Assignment operators

[Simple assignment] var zhi = 5;

[plus] var zhi = 5;zhi + = 5; Result: Zhi = 10 equals zhi = zhi + 5;

[minus] var zhi = 5;zhi-= 5; Results: Zhi = 0 equals zhi = zhi–5;

[Multiply et] var zhi = 5;zhi *=5; Result: Zhi = 25 equals zhi = zhi * 5;

[except for] var zhi = 5;zhi/=5; Results: Zhi = 1 equals zhi = ZHI/5;

[Modulus, etc] var zhi = 5;zhi%=3; Result: Zhi = 2 equals zhi = zhi% 3;

3.3 Logical operators

The result of the logical operator is only true and false two values. True also shouting truth, false is also called false.

[Logical OR, there is a true for true] var a = True;var B = False;console.log (a| | b); The result is: true

[Logical with, there is a false for false] var a = True;var B = False;console.log (a&&b); The result is: false

[Logical non] var a = True;console.log (!a); The result is: false. If true, return false, if False, return true

Here's a very interesting event to note:

When: var a = 3,b = 5,c = 7;if (a<b| | C + +) Console.log (c); output 7 C results in 7

When: var a = 3,b = 5,c = 7;if (a>b| | C + +) Console.log (c); output 8 C results in 8

For if (...) , the returned result is true because the value of C is always true regardless of the result of the previous calculation, which is converted to a logical value. and cause if (...) The result is true, but the value of C differs because the following operation is ignored when the current polygon evaluates to True.

3.4 Relational operators

The relational operator performs a comparison operation, and each relational operator returns a Boolen value of [true or false].

[Greater than]var a = 2,b = 3;console.log (a>b); return Fasle

[Less than] var a = 2,b = 3;console.log (a<b); returns true

[Greater than or equal to]var a = 2,b = 2;console.log (a>=b); return true

[Less than or equal to]var a = 2,b = 2;console.log (a<=b); returns true

3.5 three-mesh operator (conditional operator)

There is an operator in C that I call "Trinocular operator" in W3school, which is called "conditional operator". Replace the IF () with a line of characters ... else ..., in the following form:

Var zhi = condition? exp1:exp2;

It indicates that if the condition returns True (TRUE), then the EXP1 is executed, or EXP2 is executed; The common form is:

1) var Zhi = a > B? a:b;//it indicates that if a is greater than B, the value of a is assigned to Zhi, otherwise the value of B is assigned to ZHI,EXP value

2) var a = 3,b = 8,c = 5;var Zhi = a>b?b>c?c:b:a>c?c:a;console.log (zhi); Returns a decimal value of three numbers, exp is an expression

3.6 The change and the constant when the value is re-assigned

The original values in JavaScript Undefinde, nulls, Boolen, numbers, and strings cannot be changed, and any time it seems to be a re-assigned value, it actually returns a new value to the variable.

JavaScript's variables, like the data types of many other programming languages, can also be classified as "value types" and "reference types." When a variable is assigned a value, it is allocated a storage space in memory, which is used to store the value, and then the variable is directed to it. A value type is when the data is copied: a = b; a new storage space in memory, which is stored in the value of B, and then a to point to it, that is, "value copy", after the copy is completed, the value of a will not affect the B. And the reference type is when the execution: a = B, is to have a to point to the memory space that B points to, A and B share a storage space, so when the value of a is modified, the value of B will also change (so perhaps not rigorous, to make a comparison: B in order to put apples, find a box to store. Then it tells a that you can get it somewhere, and a doesn't feel good, it's replaced with a watermelon. Because B can only be picked up in that place, so it gets the watermelon.

Four commonly used function objects

Note: In JavaScript, it is case-sensitive.

Mathematical functions:

Random number: Math.random () generates a pseudo-random number greater than or equal to 0 less than 1.0

[Get a random number between 10: parseint (Math.random () *10)]

Rounding: Math.Round (5.62389)//6 returns the nearest integer

Rounding Up (flowering board function): Math.ceil (5.12313)//6 regardless of the size after the decimal point, rounding up

Rounding down (floor function): Math.floor (5.9555)//5, regardless of the size after the decimal point, rounding down

Absolute value: Math.Abs (-5)//5

Returns the large value: Math.max (1,5,6);//6

Returns the decimal value: Math.min (1,5,6);//1

Arithmetic square root: math.sqrt (4)//2

Power operation: Math.pow (2,4); 16

Keep specified decimal digits: variable. toFixed (number of decimal digits reserved)

In the operation, if the data overflows, the infinity is returned, and the operation fails to return Nan

Date-time functions

Date Created: var time = new Date ();

Results: Wed June 15:27:41 gmt+0800 (China Standard Time)

Year taken: var time = new Date (); Time.getyear (); result 114 "Current is 2014"

Take full year: var time = new Date (); Time.getfullyear (); result 2014

Take month: var time = new Date (); Time.getmonth (); Results: 5 "Current is June"

Description: The JS take month is counted from 0, so in actual use, usually year = Time.getmonth () +1

Date Taken: var time = new Date (); Time.getdate (); Results: 11 "Current is number 11th"

Take: var time = new Date (); Time.gethours ();

Take minute: var time = new Date (); Time.getminutes ();

Take seconds: var time = new Date (); Time.getseconds ();

Timestamp: var time = new Date (); Time.gettime ();

Day of the week: var time = new Date (); Console.log (Time.getday ());

Specified date: var t = new Date (2016,5,6); Console.log (T.getfullyear ());

String functions

Take length: var str = "123abc Chinese"; Console.log (str.length); This shows that both Chinese, digital, and English characters account for only one length.

Find refers to the positional character: var str = "123abc Chinese"; Console.log (Str.charat (6));//In the specified string, look for a character with an index of 6, starting with 0. [Find last character: Str.charat (str.length-1)]

String interception: var str = "123abc Chinese"; Console.log (str.substring (1,3)); Result: 23. A character that starts at the end of the specified index, starting at the specified index, when there is only one argument, that is, starting at the specified index, ending at the end of the entire character

String interception: var str = "123abc Chinese"; Console.log (Str.substr (1,3)); Result: 23a. Total number of characters to be intercepted starting at the specified index

String interception: var str = "123abc Chinese"; Console.log (Str.slice (1,3)); and substring ()

String truncation (from the last number): var str = "123abc Chinese"; Console.log (Str.slice (-1)); From the back, the specified length characters are truncated altogether.

First occurrence index position: var str = "123abc Chinese"; Console.log (Str.indexof ("a"));//3, returned when not found-1

Last seen position: var str = "123abc Chinese a"; Console.log (Str.lastindexof ("a"));//8

Finds the index position of the first occurrence of the specified character starting at the specified position: var str = "123ABCA Chinese a"; Console.log (Str.indexof ("a", 4));//returns 6. Finds the first occurrence of a specified character starting at index 4

String segmentation is an array: var str = "[email protected]; [email protected] "; Console.log (Str.split ("; ")); /Result:["[email protected]", "[email protected]"]

Group arrays by the specified string: var array = ["[Email protected]", "[email protected]"];console.log (Array.join (";")); The result is: "[email protected]; [Email protected] "

String substitution: var str = "I love China"; Console.log (Str.replace ("Love", "Love"));//The result: I love China very much. Replace the previous character with the following string [replace the previous one, which is reflected in many places of JS]

All English caps converted to lowercase: var str = "Abcabc Chinese"; Console.log (Str.tolowercase ());//Result: ABCABC Chinese

All English lowercase converted to uppercase: var str = "Abcabc Chinese"; Console.log (Str.touppercase ());//Result: ABCABC Chinese

In addition, if you want to access the value of a specified index in a string, you may also access the same as an array. Like what:

var str = "Abcderg"; Console.log (str[2]); The returned result is: C

However, it is important to note that this approach is not supported by IE8 browsers.

Array functions

All operations return undefined when the array is empty. Array index starting from 0

Array: var arr = [n/a];

Delete the first index (subscript) Value: Shift ();

var arr = [1,2,3];var t = Arr.shift (); Console.log (t); Console.log (arr);

Value: t = 1;arr = [2, 3]

Add one or more values to the front of the array: Unshift ()

var arr = [1,2,3];var t = arr.unshift ( -1,0); Console.log (t); Console.log (arr); t = 5 arr =[-1, 0, 1, 2, 3]

Delete last index value: Pop ()

var arr = [1,2,3];var t = Arr.pop (); Console.log (t); Console.log (arr); t = 3 arr = [1, 2]

Add one or more values to the end of the array: push ()

var arr = [1,2,3];var t = Arr.push ( -1,0); Console.log (t); Console.log (arr); t = 5 arr t = [1, 2, 3,-1, 0]

remove element: Splice (,)

Removes a value of the specified length, starting at the specified position

var arr = [1,2,3,4,5,6];var t = arr.splice; Console.log (t); Console.log (arr); t = [2, 3] arr = [1, 4, 5, 6]

The function is also used in a way that starts at the point of deletion and inserts one or more elements

var arr = [1,2,3,4,5,6];var t = Arr.splice (1,2,7,8,9); Console.log (t); Console.log (arr); t= [2, 3] arr = [1, 7, 8, 9, 4, 5, 6]

That is, starting with the third argument, separated by commas, are the values to be inserted

Inverse value function: reverse ()

var arr = [1, 7, 8, 9, 4, 5, 6];var t = Arr.reverse (); Console.log (t); Console.log (arr); t = [6, 5, 4, 9, 8, 7, 1] arr = [6, 5, 4, 9, 8, 7, 1]

Sort function: Sort ()

var arr = [1, 7, 8, 9, 4, 5, 6];var t = Arr.sort (); Console.log (t); Console.log (arr); t = [1, 4, 5, 6, 7, 8, 9] arr = [1, 4, 5, 6, 7, 8, 9]

String continuous intercept function: Slice (start index, end index)

Note: The end index is the index value, starting with 0, rather than the length of the total intercept

var arr = [1, 7, 8, 9, 4, 5, 6];var t = arr.slice (2,6); Console.log (t); Console.log (arr); t = [8, 9, 4, 5] arr = [1, 7, 8, 9, 4, 5, 6]

It is important to distinguish between splice (,) and slice () two functions. Splic (,) is the deletion of an array element, while slice () returns the value to intercept from the original array, but the original array content remains unchanged

Convert a string to an array: split (delimited string)

Note: Not all strings can be converted to arrays, and when using splice (), the parameter "delimited string" must be correctly

var str = "1,2,3,4,5,6"; var t = str.split (","); Console.log (t); Console.log (str); t = ["1", "2", "3", "4", "5", "6"] str = "1,2,3,4,5,6"

Five Type conversions

As a weakly typed language, JavaScript has a very flexible value type.

said in advance: The following "variable" does not necessarily refer to a variable, also the same time refers to the direct volume of a data type [direct volume: The data value directly used in the program, such as Integer 1, string: "str", etc.].

5.1 Various types of conversion modes

Convert to String: variable. toString (), string (variable), variable. Join (Array)

Convert to Numeric type: parseint (variable), parsefloat (variable), number (variable)

Convert to date type: new Date (variable)

Convert to Boolean: Boolean (variable)

Convert to array: variable. Split ("delimiter")

These conversions may not be strict, and some even have preconditions. For example: To convert an array, the first requirement is that the variable must be an array. But these are very effective in practical applications.

5.2 Converting the corresponding table

Note: For situations that cannot be converted, it is not possible to convert directly. Some can be converted in an indirect way.

Variable

Converted to
String

Converted to
Numeric type

Converted to
Boolean type

Converted to
Date type

Converted to
Array

var t = "S;t;r"

String

"S;t;r"

NaN

True

/

Str.split (";");

Result:["s", "T", "R"]

(only by; split)

var t = 1.1;

Numerical

"1.1"

parseint (t)

Results: 1

Parsefloot (t)

Results: 1.1

Number (t)

Results: 1.1

Not 0 is True

When 0 o'clock, the result is false

/ /

var t = true;

(Boolean value)

True

Is true, the value is 1

is false, the value is 0

True

/ /

var t = new Date ()

(Date-time type)

Hu June 10:49:33 gmt+0800 (China Standard Time)

1402541401307

(Get time stamp)

True

Hu June 10:49:33 gmt+0800 (China Standard Time)

/

var t = null;

(Null)

Null

0

False

/ /

var t = undefined;

(undefined)

Undefined

NaN

False

/ /

Var t = function () {THIS.T = 3;};

function

Returns the entire function

function () {THIS.T = 3;}

NaN

True

/ /

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.