JavaScript Scattered notes

Source: Internet
Author: User
Tags array sort blank page

JavaScript basics

JS composition: DOM BOM ECMAScript

ECMAScript: "Translation function" JS in the most central part of the profession is called the interpreter almost no compatible
Dom:document Object Model ability to manipulate HTML---"Document has some incompatibilities
Bom:browser Object Model Operation browser capability---"Window compatible source

Type of variable: Number string Boolean function object undefined (undefined/undefined not assigned)

Variable Type conversions:
Explicit type conversions (coercion type conversions):
parseint ()----match a string from left to right, presenting the first digit in the string
If there is no number in the string, a Nan is returned; Nan and nan are not equal
Parseint will convert decimals to integers, with parsefloat () for decimals

Implicit type conversion: 5== ' 5 '---"True
' 12 ' + ' 5 ' =125 Plus for string connection '-'-' 5 '---7

Scope and closure of variables:

Scope: Local variable: can only be used within a function that defines the variable
Global variables: Declared outside of all functions

Closures: Child functions can use local variables of the parent function

JS naming specification:
Readability---can read
Normative---conform to rules
Hungarian nomenclature:
Type prefix: Array (a), Boolean (b), floating-point number (f), function (FN), Integer (i), Object (O), regular (re), string (s), font variable (v)
Initial capitalization: Hump naming

Operator: modulo%----application (seconds turn into time)
var s = 156; Alert (parseint (S/60) + ' +s%60+ ' seconds ')
!== and = = = the opposite meaning
Program Flow control:
Judging----if,switch,?:
Switch (variable) {
Case value 1:
Statement 1;
Break
.......
Default
Statement
}

Trinocular (yuan) operator:?:
Conditions? Statement 1: Statement 2

Jump: Break breaks the entire statement
Continue interrupt this time, continue to perform the following
True:
True: true, not 0 digits, non-empty string, non-empty object
False: Flase, numeric zero, empty string, empty object, null,undefined

json:{} based on JS, used to save data
Arrays and JSON loops: for (var i in Arr/json) {};

The return value of the function:
Return returns a number, string, etc. inside a function, returning only one type of value at a time
function parameter arguments (variable parameter/indefinite parameter)
Function summation:
function sum () {
var result = 0;
for (Var i=0;i<arguments.length;i++) {
Result + = Arguments[i];
}
return result;
}
SUM (2,4,5,7,24,756,34); The number of n can be placed in parentheses in---

Take non-inline styles:
When the style is written between the lines, it can be taken directly through the oDiv.style.xxx.
Non-inline style via oDiv.currentStyle.xxx (IE), but compatibility issues exist
getComputedStyle (Odiv, the second parameter casually put null/false). width
Simple and compatible processing
if (Odiv.currentstyle) {
ODiv.currentStyle.xxx
}else{
getComputedStyle (Odiv, the second parameter casually put null/false). width
}

function GetStyle (obj,attr,value) {
if (!value) {
if (Obj.currentstyle) {
Return Obj.currentstyle (attr)
}else{
Obj.getcomputedstyle (Attr,false)
}
}else{
Obj.style[attr]=value
}
}


Styles in CSS
Compound styles such as: Background,border
To go to the compound style is to use concrete such as Backgroundcolor,bordercorlor
Single style such as: Width,height

Array Basics:

var a = new Array or var a = [[+]

The length of the array can be either read or write, such as length=0 to empty the array

Add push () to the end of the array and add it after the array
End of array Delete pop ()--delete array last number

Array header add Unshift ()
Array header Delete Shift ()

Array Delete Splice (start, length)
Arr.splice (2,3)---> Three elements are removed from the second element
Arr.splice (2,3,a,d,e)---> Start with the second element, three elements are deleted, and the ADE is added

Array Connections concat ()---> a.concat (b) A, a, two arrays
Array concatenation join ()---> a.join ('-') A is an array
Array sort () first start from small to large (a,b,c,d,..... ; 12,2,34,9,... )
Sort () only knows the string, which has a function parameter;

Sort (function (n1,n2) {
if (n1<n2) {return-1};
else if (n1>n2) {Retuan 1};
else {return 0};

or return n1-n2;
})

Timer:
SetInterval () Timer
SetTimeout () Delay timer

Clearinterval (name) off timer
Cleartimeout (name) off delay timer


Date Time
var odate = new Date ();
Odate.gethour s ()//Get Hours

The functions of CharAt () and [] are the same

Dom Basics:

FF Support Rate 99%
IE ie6-8 10%
Chrome 60%

Child node ChildNodes (text node + element node) empty line or line wrap also count nodes in Ie6-8 no problem
NodeType node type
NodeType--->3 text node
NodeType--->1 element node

The Children element node is only the first-level node, so there are nodes in the child nodes that do not count

Parent node ParentNode (text node)

OffsetParent gets to the relative location of that parent

FirstChild Low version IE version support
Compatibility issues Firstelementchild Other versions browser support, same as
Lastchild/lastelementchild

Nextsibling/nextelementsibling
Previoussibling/prviouselementsibling


There are three ways to manipulate element attributes
1,. Method any occurrence of the place can be replaced by []
2, [] the scheme
3, SetAttribute (name, value) getattribute (name) removeattribute (value)

CreateElement document.createelement (' Li ')

AppendChild insert element, element is added last Ul.appendchild (child node)
First remove the element from its original parent and insert it into the new parent
InsertBefore insert Element, Ul.insertbefore (child node, before WHO)

RemoveChild Delete element Ul.removechild (child node)


Document fragmentation 1, creating a document fragment Document.createdouementfragment ();
2. Put the created element in the document fragment
3. Inserting document fragments into an element

Table Application
You can get the table's tbody,thead,tfoot, rows, and columns by tbodies/thead/tfoot/rows/cells
Search:
Ignore case-------toLowerCase ()
Fuzzy search-------Search so that the content of searches is not 1
var str = ' abcdef '; Str.search (' A ') returns the position subscript value, cannot find return-1
Multi-Keyword Search
Split () cut a string into an array

Sort:
Principle: The value of the content to be sorted into a vegetarian group, then sorted with sort (), and finally inserted into the original sequence using the AppendChild () method

Form Application
To submit data to the server, the name in the form is important, and the background uses name to find
Event: OnSubmit occurred while committing
Occurs when OnReset resets

JS Motion Basics
The use of Timers

The timer is best to turn off the timer before each run, ensuring that only one timer is running
Stop timer and start movement separate, separated by If/else
Transparency
Filter:alpha (opacity:30); opacity:0.3

When writing a buffer, be sure to take the whole speed


Multi-Object Motion frame
Multi-object open multiple timers;
Everything can't be shared.


Event Object
Document represents the entire Web page,
Event.clientx/event.clientx mouse click on the horizontal ordinate position, Firefox incompatible
Scrolling events
Window.onscroll = function () {}
Window Change events
Window.onresize = function () {}

Event Flow
Block event bubbling E.cancelbubble=true

Mouse events
Experience: Whenever used to clientx and clienty must add scrollleft,scrolltop;

Keyboard events
KeyCode Keyboard Code table
Altkey/shiftkey/ctrlkey
CTRL + ENTER----Send message if (E.keycode = = && E.ctrlkey) {...}
Onkeydown/onkeyup
Default behavior
OnContextMenu Right-click menu events
Document.oncontextmenu = function () {return false}---> Right-click menu disappears

Event Bindings
IE mode attachevent (event name, function)
Div.attachevent (' onclick ', function () {...})

Chrome/ff mode AddEventListener (event name, function, false/true)
Div.addeventlistener (' click ', function () {...},false)

Unbind events
IE mode DetachEvent (event name, function)
Chrome/ff mode RemoveEventListener (event name, function, false/true)

Prohibit text selection
return False CHROME/FF
Obj.setcapture () IE dedicated

Event capture sets all events in a webpage to an element
SetCapture ()

Dismiss event capture
Obj.releasecapture () IE dedicated


Object: Like a black box, not understanding the internal structure, but know the various operations of the surface
Object-Oriented (OO): uses its features without understanding the internal principles

Object-oriented features:
The person who used the object and the person who wrote it
1, Abstract: (pumping)-"the object inside the core of the characteristics of the extraction to deal with, seize the core issues
2, Package: Do not consider the internal implementation, only consider the use of functions (see what is inside, with good surface function)
3. Inheritance (inherited): On existing objects, inherit new objects (from inheriting some methods and properties from the parent class, subclasses have their own attributes)

Multiple inheritance: Methods and properties that inherit multiple parent classes
Polymorphic: JS not commonly used


The composition of the object:
Method:---Function: process, dynamic
Properties:---Variables: state, static

This: the object on which the current event occurred
Who the current method belongs to and who it belongs to

You cannot arbitrarily attach methods or properties to system objects, otherwise overwrite existing methods and properties
Object objects
There are no properties and methods on object objects, and you can implement object-oriented by adding functionality above it.

Factory mode (raw materials, processing, factory)
Question: no new
function repetition--waste of resources


Prototype prototype:
CSS class---> Add style to a group of elements at once
Inline style---> one element at a time style

Prototypes are the same concept as class.


Class, Object
Class: (Die)
Object: (Finished)
Example: var arr = new Array (1,1,3,4,5,4)
Array----> class
ARR------> Objects


Summary: Using the constructor plus the attribute, using the prototype plus method

Object-oriented (monomer) implementation in JSON, simple, but not suitable for multiple objects

Namespaces: You can have functions of the same name exist simultaneously, using JSON to implement

Change procedure-oriented functions to object-oriented
Process-oriented programs that are rewritten as object-oriented programs cannot have function nesting
Window.onload initializes the entire program to a constructor to initialize the entire object
Changing a process-oriented variable to a property
Change a process-oriented function to a method


Inherited:
Call ()


System objects:
Local object: (non-static object) Array,object,function,number ..., need new
Built-in objects: (Static objects) Math,global no need to be new, directly
Host object: Object DOM BOM provided by the browser


Bom
Open the Window window.open (' http://www.baidu.com ', ' _self ');
The second parameter is the way to open
window.open (' About:blank '); Open a blank page
Close the window window.close (' http://www.baidu.com ');
document.write (' abc ')---> First empty, write content

Common Properties
Window.navigator.userAgent Current Browser version
Window.location the address of the current Web page
window.location = ' www.baidu.com ' can also be used to assign values, jump to a new page

Size/Distance
Document.documentElentment.clientWidth Viewable area width

Document.documentElentment.scrollTop page scroll up and down distance
Document.body.clientWidth

System dialog box
Select box: Confirm ("contents of question"), return Boolean
Input box: Prompt (), return string or null

COOKIE: A page used to hold information
Features: one set of websites (same domain) with only one set of cookies
Quantity (<50 data), limited size (4k-10k)
Expiry time

Document.cookie;
Data Format is Property = property value
Cookies will not be overwritten, two will show two

Regular expressions (set of rules): Powerful string Matching tool
Search ()
SUBSTRING ()
CharAt () returns a bit of a string
Split ()

Match () extracts all matching content
Replace () Replacement

[] or
^ Except, exclude
Go out the regular re =/<[^<>]+>/g of the HTML tag
{n} occurs exactly n times
{n,m} at least n times, up to M times
{N,} at least n times, up to an unlimited number of times
? Represents {0,1}
* indicates {0,}

JavaScript Scattered notes

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.