Web Foundation-javascript

Source: Internet
Author: User
Tags array length mathematical constants string format

                                               JavaScript
Jsto add features to a Web page:
1, the dynamic effect of the page: input validation, dynamic display of page elements, etc.
JavaScript is written on an HTML page and is run by a browser.
2. Server interaction: Exchange of Data--jsp, Ajax
jquery--Packaging Good JS method
I. Overview
   1. What is JavaScript?
Web programming techniques for adding interactive behavior to HTML pages
JS is an object-based and event-driven explanatory scripting language with syntax similar to Java and C language
Features: Embed HTML page directly, interpret execution code by browser, do not precompile
Features: Calculations for client-side data
Legitimate validation of client forms
Triggering of browser events
Web page special display effect production
   2. History
JavaScript is exactly the name of ECMAScript, which is developed and maintained by the ECMA organization
ECMA-262 is a formal javascript.
This standard is based on JavaScript (Netscape) and JScript (Microsoft)
-Netscape first introduced JavaScript in Netscape2.0
-Microsoft started providing support for client-side JavaScript at IE3.0 and named JScript
second, the basic grammar
  1, the wording:
<1> inside elements and events bound together <input type= "button" value= "buttons" onclick= "alert (' Hello java ') ' >
<2> is encapsulated in the head tag in <script language= "JavaScript" ><script>, plus language is a way to tell the browser to use the browser default settings if not written
<3> package in JS file when called <script language= "JavaScript" src= "Myscript.js" ><script> Note: The recommended use of type=text/ Javascrpt
  2. Error Viewing Method:Firefox error console
Note: Single-line comments//Multiline Comments/* * *; statements are made up of expressions, keywords, operators; case sensitive; semicolon ends
  3. Variables
Declaration of the <1> variable: var x=0;var y= "Hello"; var z= "true" variable is not determined at the time of declaration, the data type is determined when assigning a value JS is a weak type of programming language
   4. Data type
     <1> Basic types:Number/string/boolean
String: A sequence of unnicode characters, numbers, and punctuation
Enclosed in single or double quotes-two can be used, but if the outer layer is double quotation marks, the inner is single quotes because it is easy to distinguish
Special characters need escape characters \, such as \n,\\,\ ', \ "
How to indicate that the range of Chinese characters is only Chinese and must be used UNICODE:[\U4E00-\U9FA5]
Number: integer and floating-point values are not distinguished
All numbers are stored in 64-bit floating-point format, similar to double format
         A, integral type
10 binary integers consist of a sequence of numbers
16 binary data front plus 0X, octal front plus 0
        B, floating-point type
Using the decimal point record data: 3.4
Using scientific notation to record data: 4.3e23
         C, Boolean:More for control statements
Conversion of data types:
Implicit conversions: direct-to-default rules
Rule: number+string=string
Number+boolan=string true turns 1 false to 2 operation
Boolean+string=string true/false into a string type True/false
The Boolean+boolean=number value is the number 0/1
Explicit conversions: Using the Function method of transformation-when there are definite calculation requirements
Rule: A, toString
B, parseint ()
C, parsefloat ()
The default data type entered from the console is a string type
D, IsNaN ()--judging is not a number is very common
typeof: Judging the type of data
    <2> Special Types :null--null/undefine--not defined
<3> Complex Types
   5. Operators: Arithmetic, logic, relationship ...
<1> Relational operators note the difference between = = = Strict equality and = =
= = = The value and type are equal
   6. Process Control:
third, common built-in objects
   what is a JS object?
JS is an object-based language
Object is the most important element in JS.
JS contains a variety of objects: built-in objects, custom objects, browser objects, HTML DOM objects, active objects
   1. Simple Data Objects
String:
         <1> Create a String object:var str1= "Hello World", var str2=new String ("Hello World");
         properties of the <2>string object:Length alert (str1.length);
         Methods for <3>string objects:
toLowerCase ()/touppercase () Case Conversion
IndexOf ()/lastindexof () find the location of a sub-character--from the location of the search/find a character--from behind to find
SubString (Star,end) intercepts the string without the end itself position
CharAt (Index) returns the string that specifies the subscript
charCodeAt (Index) returns a string Unicode encoding
Replace (original character, new character) can only be replaced once
Split () splits the string to return an array of
   action: Simulate filtering of sensitive characters

            functionreplacestring () {//Get string First              varStr1=document.getelementbyid ("Txtstring"). ValuevarIndex=str1.indexof ("JS");//set the initial value               while(index>-1) {//If there are sensitive charactersStr1=str1.replace ("JS", "*");//I found the replacement of the sensitive characters.Index=str1.indexof ("JS");//continue to find out if there is a sensitive character JS in the new string, which is equivalent to an iterative operation                } document.getElementById ("Txtstring"). value=str1}


Ways to filter sensitive characters: <input type= "text" onblur= "replacestring ()" id= "txtstring"/>
Number: Wrapper object for basic type data
Method: ToString (): numeric value converted to string
Tofixed (): numeric value converted to a string, parameter reserved for the specified number of decimal digits, rounded, not satisfied with the number of reserved digits, complement 0
such as Var data=53.2-->data.tofixed (2)-->53.20 is commonly used for decimal formatting
Boolean:
   2. Combining Objects
Array:1 column multiple Data js without a collection only the array does not need to declare the initial length directly with
        <1> wording:
Way One AR arr=new Array ();//first declaration not initialized
Arr[0]= "Marry" arr[1]=true
Mode two var arr=new Array ("Mary", 10,true) declaration + initialization
Way three var arr=["Mary", 10,true] shorthand omit new Array
<2> properties: Length Gets the number of elements/array length
        <3> Array Method:
The arr.tostring ()---is used to iterate through an array, output an array such as 10,20,21: The default is comma-separated attention is not a parameter
Arr.join ("*")---Specify the separator * Output array 10*20*30
Arr.concat (value1,value2,...) concatenated array after the original array to get the new array the original array value does not change
Arr.slice (start,end)--Gets the array of sub-arrays/intercept arrays with no end position
Arr.reverse ()--inverse of the array
Arr.sort ()--sorting is sorted by character order by default
If you want to implement a numeric sort, you need to customize the method:
function Arrayfunc (A, b) {
return a-B;
}
Array.Sort (Arrayfunc) passes the method object as a parameter
Math: Math-related--no need to create objects directly using similar static objects
        <1> Common Properties:It's all mathematical constants.
math.e--Natural Number
math.pi--Pi
MATH.LN2 (in2)
Math.ln10 (IN10) ...
         <2> Method (Learn)
Trigonometric Math.sin (x) math.cos (x) ...
Inverse trigonometric function math.asin (x) Math.acos (x):
Calculate function math.sqrt (x) Math.log (x):
Numeric comparison function Math.Abs (x) Math.max (X,yxz ...) ...
Note One of the following: Math.random ()--0<=math.random () <1 decimal
Math.floor ()--Returns an integer less than or equal to the specified number, which means
Math.ceil ()--just opposite to the upper rounding
Case LIST: 3-9 random integer var s= (Math.random ()) *6+3--> Math.floor (s)
Can be applied to a random occurrence of a picture on a webpage, coordinates generate random numbers
Date: Object
        <1> Create objects:
var d=new date ();//Current date and time
var d=new date (2013/01/01 12:12:12);//fixed date and time
         <2> Method:
Category: GetXXX
Getday/getdate/getmonth/getfullyear ...
Setxxx
Setday/setdate ...
toxxx--to get a representation of the string format is often used for page display
Tostring
  3. Advanced objects:
Functions: A function (method) is a set of statements that can be run anywhere, any function object can represent the developer of any functional function is actually a full-featured object
Definition: Slightly
Call:
Arguments object:
A, JS in the traditional sense of overloading (the same method name, the parameter list is different), if the method name is the same, the last definition as the standard
B, JS if you want to implement a similar overloaded effect using the keyword arguments to represent the currently passed-in parameter, an array is formed
function m () {alert (arguments[0])}
  

//Overloading of methods: function          TestMethod () {  if(arguments.length==1) {  var data=arguments[0];          Alert (Data*data);        }  Elseif(arguments.length==2) {alert (arguments[0]+arguments[1]); }}


To create a method:
Mode one: function keyword function s (parameter) {method body}--recommended
Methods for function-related
Mode two: Var f =new Function ("A", "B", "Alert (a+b);"); --Not recommended for use
The last parameter is the method body, and the other parameters above are the parameters of the method
Existing requirements: Some methods do not require explicit presence, but are used separately for other methods
 

       function          ArraySort () {  var array=[12,34,56,11,7];  var f=New Function ("A", "B", "return a-B;") // specifically for sorting by value              Array.Sort (f);        Alert (array.tostring ()); }              


         

Way three:

var f =new Function (A, b) { return A-A; use anonymous function }


Global functions: All JS objects can be used
Parseint/parsefloat/isnan ...
encodeURI (): Encode the string as a URI
decodeURI (): Decodes a URI encoded by the encodeURI () function
Eval: Calculate var s1= "1+3*5"; var r =eval (S1); alert (r);//16
Calculate a string to get the result, or execute the JS code in it

REGEXP: A plain text expression that indicates that a matching pattern is performed in a different locale, using regular expressions to implement various processing of text
Eplace (original character, new character);
Match ()--the result of matching is stored in an array
Search ()--Get a matching subscript to determine if there are sensitive characters
Match mode: G--global Global
M--multilin Multiple lines
I--ignorance ignoring case
Practical application: Str1=str1.replace (/js/gi, "*")//global substitution ignoring case
Str1=str1.replace (/\d/g, "*")//\d represents a number if 1 or more digits are represented by/\d+/
The application of regular expressions is divided into two categories:
Class: Used in conjunction with three methods of a string object to implement a string operation

Class Two: Regular Expression objects
var r =/\d{6}/--6 decimal places
var s=/^[a-z]{3,5}$/means A-Z 3-5-bit matching from start to finish
R.test (String)--true/false means whether the specified range matches the data entered--especially for input validation
Verifying Kanji:/^[\u4e00-\u9fa5]{3}$/3 Kanji

Iv. Application (important)
dhml--dynamic effects such as browser browsing information, screen information, etc.
The entire window is implemented as an object with the following structure:
Window Parent Object
Document---HTML
Screen
History
Location
Event
Navigator
   1. Window object:
       <1> Open the dialog window : alert (); Is a method of blocking threads Window.alert ("Hello");
Window.confirm ("Please confirm")--Confirm Inquiry window information prompt--return Boolean
Learn about Window.prompt ("Please enter:")--pop up an input text box seldom use cannot modify the style of the text box, control
       <2> Open a new window:A parameter window.open (URL);--window.open ("http://www.baidu.com"); repeat Open
Two parameters window.open (URL, "Windowname") take the name of the window and click it again to not open it again.
Three parameters window.open (URL, "Windowname", conf) the last parameter for browser appearance settings such as wide high ...


Web Foundation-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.