js
The complete javascript is ECMAScript (syntax)
Browser Objects (DOM BOM) properties.
// Single line comment
/**/ Multi-line comments
Everything in ECMASxript (variable function names and operators) is case sensitive
1: What is an identifier?
变量 函数 属性的名字 或者函的参数
2: Indicator naming rules
有字符 数字 下划线 或 $ 符号组成
不能以数字开头
不能使用关键字 保留字 作为标识符
1: Variable declaration var
变量的声明要使用var 操作符
语法 var 变量名
2: Variable assignment
声明同时赋值 var 变量名 = 值
先声明后赋值 : 变量名 = 值
illustrate
1: Variables declared by omitting var are global variables
2: It is not recommended to omit the var operator to define global variables
javaScript data types
ECMAScript
Five simple data types Undefined NUll Boolean NUmber String
Complex data type Object
typeof function detects command type
Return value string number boolean object undefined function
undefined
The undefined type has only one value, the special undefined
illustrate
Generally speaking, there is no need to explicitly set a variable to undefined.
null
1: null value represents a null object pointer
2: If the defined variable is going to be used to save objects in the future, it is best to
初始化为null 而不是其他的值
When specifying the undefined value, the derived word null is worth the value, so undefined == unll
的返回结果是true
1: Master Number
2: Master isNAN()
3: Master numerical conversion
Number()
parseInt()
parseFloat()
Number: represents an integer or floating point number
NaN: Not a Number (Not a Number) is a special number
illustrate
1: Any operation involving NaN such as (NaN/10) will return NaN
2: NaN is not equal to any value including NaN itself.
isNaN
Syntax isNaN(n)
Function: Detect whether n is "non-numeric" Return value boolean
Parameters: Parameter n can be of any type
Description isNaN() first attempts to convert the accepted value into a numeric value, and then detects whether it is a non-numeric value.
Numeric conversion
1: Number() can be used for any data type
2: parseInt() and parseFloat() are specially used to convert strings into numerical values.
3: The string operated by parseInt() must start with a number.
4: parseInt() will ignore spaces in front of the string until it finds the first non-space
illustrate
parseInt()转换空字符串返回NaN
parseInt()这个函数提供第二个参数 转换时使用基数 即多少进制
pressFloat
parseFloat: Parse from the first character to each character until an invalid one is encountered
up to floating point numeric characters
illustrate
In addition to the valid first decimal point, the second difference between parseFloat() and parseInt() is that
Leading zeros are always ignored
String
grammar
str.toString()
Function: Convert str to string
1: Master String
2: Master string conversion
String()
toString()
3: Master Boolean
4; Master type conversion
The String type is used to represent a sequence of zero or more 16-bit Unicode characters.
That is, string strings can have single quotes or double quotes, which must be used in pairs.
Syntax str.toString()
Function: Convert str to string
Returns a copy of str
Parameters: str is the content to be converted, which can be a numerical value, a Boolean value, an object, and a string.
illustrate
When you don't know whether the value to be converted is null or undefined, you can also use the String () function, which can convert any type of value into a string.
type conversion
1: All numbers except 0 are converted to boolean true
2: All characters except " " are converted to Boolean type and are true
3: null and undefined are converted to false
learning target
1: Master what an expression is
2: Master the classification of javascript operators
3: Master arithmetic operators
what is expression
Data of the same type (such as constant lights, variables, functions, etc.) are understood according to certain rules using operation symbols, and meaningful formulas are called expressions.
Operator classification
1: Arithmetic operators + - *, / %
2: Logical operators
3: Assignment operator
4: Comparison operator
5: Ternary operator
increasing and decreasing
1: Increment
++a and a++ both perform increment operations on a
the difference
++a first returns the value of a after incrementing
a++ first returns the original value of a, then returns the incremented value.
assignment operator
Simple assignment =
Compound assignment += -= *= /= %=
comparison operator
< >= <= == === != !==
== Equality only compares whether the values are equal
=== Equality comparison is worth simultaneously comparing whether the data types are equal.
!= Whether the unequal comparison value does not want to wait
! == Inequality comparison is worth comparing whether the data types are not equal at the same time.
Return value: boolean type
ternary operator
grammar
condition? Execute code 1: Specify code 2
illustrate
Can replace simple if statement
If the condition is true, specify code 1, otherwise execute code 2
Logical operators
&&: AND (as long as one condition is not true, return false)
illustrate
In the case where the first operator is not a Boolean value, the logical AND operation does not necessarily return a value.
1: If the hermit type of the first operand is converted to true, the second operand is returned.
2: If the hermit type of the first operation is converted to false, the first operand is returned directly.
3: As long as there is null undefined NaN, null undefined NaN will be returned.
||: or (as long as one condition is true, return true)
1: If the first operation hermit type conversion type is true, the first operand is returned
2: If the first operation hermit type conversion is false, return the second operand
3: If both operands are null NaN undefined, return null NaN undefined.
! :No()
illustrate
No matter what data type the operation is, logical negation will return a Boolean value.
! ! When using two logical operators at the same time
The first logical NOT operation will return a boolean value regardless of the operation.
The second logical negation negates the boolean value
1: Master how to obtain the day of the week
2: Master document.write()
3: Master the conditional statement switch
Syntax: new Date().getDay()
Function: Get the day of the week
Return value: number(0-6)
switch statement
grammar
switch (){
case value : statement
break ;
case value : statement
break;
default:statement
}
output
Syntax: document.write("content")
Function: output content to the browser
for statement
grammar
for(statement; statement 2; statement 3){
block of code being executed
}
Statement 1: Executed before the loop (code block) starts
Statement 2: Define the conditions for running the loop (code block)
Statement 3: Executed after the loop (block of code) has been executed
for nesting
1: When the outer layer is false, the inner layer will not be executed.
2: The restrictive outer city executes the inner layer until the condition of the inner layer is false and then returns to the outer layer for execution.
do-while statement
statement
do {
Code that needs to be executed
}while (condition)
Specifies that a loop with this syntax must be executed at least once
for is a loop body suitable for a certain number of loops
while loop body suitable for the number of position loops
1: Master the application of break statement
2: Master the application of continue statement to end this cycle
Functions in javaScript
1: Master the role of functions
2: Master the definition of functions
3: Master function calls
What the function does
Any number of statements can be encapsulated through functions, and they can be used anywhere and at any time
call execution
function functionName([arg0,arg1,...agrn]){
}
illustrate:
1: functionName is the function name to be defined and belongs to the identifier
2: arg0, arg1 in []. . . argn is the parameter of the function
3: [] indicates that the content inside is not necessary, it is not syntax
return the return value of the function
Any function returns a value through the value returned by the cultivator after the return statement.
illustrate
1: The function will stop and exit immediately after executing the return statement.
2: The return statement can also not have any return value, which is used to stop function execution in advance and does not need to return a value.
learning target
1: Master arguments
Parameters in ECMAScript are represented internally by an array
Access this array parameter through the arguments object in the function body
illustrate
1: The arguments object is similar to an array and is not an instance of Array.
2: [] syntax accesses each of its elements
3: The length attribute determines the number of parameters passed
Built-in objects in javaScript
1:Array
2:String
3:Math
4:Date
Array
1: Master how to create arrays
2: Master the reading and writing of array elements
3: Master the length attribute of the array
There are two basic ways to create an array
1: Use Array constructor
Syntax: new Array()
Parentheses () description
(1) Know in advance the number of items to be saved in the array
(2) Pass the items that the array should contain to the Array constructor
2: Use array literal notation
There is a pair of square brackets [] that contains array items, and multiple array items are separated by commas.
Reading and writing array elements
When reading and setting values, use square brackets [] and provide the corresponding index
Description: The index is a positive integer starting from 0
array length
Syntaxarray.length
Function: Get the length of array array
Return value: number
illustrate
1: You can remove items from the end of the array or add new items to the array by setting length
2: When a value is placed at a position beyond the current array size, the length value of the array will be recalculated, and the length value is equal to the last index plus 1.
Master the stack method of arrays
1:push()
2:unshift()
3:pop()
4:shift()
push()
grammar
arrayObject.push(newele1,newele2,....,neweX)
Function
Add its parameters sequentially to the end of arrayObject
return value
Adds the specified value to the length of the array or array
unshift()
grammar
arrayObject.unshift(new1,new2,...,newX)
Function:
Add its parameters to the beginning of arrayObject sequentially
return value
Adds the specified value to the new length of the array
pop()
grammar
arrayObject . pop ( )
Function
Delete the last element of arrayObject
return value
the element that was deleted
shift()
grammar
arrayObject.shift ()
Function
Delete the first element in arrayObjectr
return value
the element that was deleted
join()
grammar
arrayObject . join ( separator )
Function
Used to put all elements of an array into a string
return value
String.
reeverse()
grammar
stringObject.reverse()
Function
Used to point to the order of elements in an array
Return value: array
sort()
grammar
arrayObject.sort(sortby)
Function
Used to sort array elements
Return value: array
Note:
1: Even if each item in the array is a numerical value, the sort() method compares strings.
2: The sort() method can accept a comparison function as a parameter
sort(function(){a,b} return a<b)
1: Master the operation methods of arrays:
concat()
slice()
concat()
grammar
arrayObject.concat(arrayX,array<x,.......,arrayX)
Function:
Used to join two or more arrays
return value
array
slice
grammar
arrayObject.slice(start,end)
Function:
Returns selected elements from an existing array
parameter
start (required) specifies where to start selecting. If it is a negative number, it starts from the end of the array.
end (optional) specifies where to end the selection, which is the array subscript at the end of the array fragment.
illustrate
1;If end is not specified, the split array contains all elements from start to the end of the array
2: If the parameter in the slice method has a negative number, add the number to the length of the array to determine the corresponding position.
Return value: array
learning target
1: Master the use of splice() method to delete array items
2: Master the use of splice() method to insert array items
3: Master the use of splice() method to replace array items
delete
grammar
arrayObject.splice(index,count)
Function
Remove zero or more elements starting at index.
return value
array containing deleted elements
illustrate
count is the number of items to elucidate, if set to 0, no items are removed.
If not set, deletes all values starting from index
insert
arrayObject.splice(index,0,item1,.....,itemX)
Function
Insert value at specified position
parameter:
Index: starting position
0: Item to be deleted
item...itemX: The item to be inserted
Return value: array
replace
grammar
arrayObject.splice(index,count,item,....,itemX)
Function
Inserts a value at the specified position while removing any number of items
parameter
index: starting position
count: number of items to delete
item, ....., itemX: The item to be inserted
Return value: items removed from the original data (returns an empty array if no items were removed)
learning target
1: Master the ECMAScript method of adding two positions to an array instance
indexOf()
lastIndexOf()
indexOf
grammar
arrayObject.indexOf(searchvalue,startIndex);
Function
Search backwards starting from the beginning of the array (position 0).
parameter
searchvalue: the item that must be found
startIndex: index of the optional starting position
return value
number The position of the searched item in the array. If not found, -1 is returned.
lastIndexOf()
grammar
arrayObject.lastIndexOf(searchvalue,startIndex)
Function:
Search forward starting from the end of the array
parameter
searchvalue: required, the item to be searched for
startIndex: optional, the index of the starting position
return value:
number, the position of the searched item in the array, returns -1 if not found
learning target
1: Master the methods of string objects
charAt()
charCodeAt()
indexOf()
lastIndexOf()
charAt() and
grammar
stringObject.charAt(index);
Function:
Returns the character at index position in stringObject
charCodeAt()
grammar
stirngObject.charCodeAt(index)
Function
Returns the character encoding of the character at index position in stringObject
ECMAScript5 uses "square brackets plus character index" to access specific characters in a string
However, IE77 and earlier browsers will return undefined
learning target
1: Master the interception method of string objects
slice()
substirng()
substr()
grammar
stringObject.slice(start,end)
Function
Intercept substring
Parameter Description
1: start: required, specifies the starting position of the substring
2: end: Optional indicating where the substring ends, end itself is not within the interception range
, truncate to the end of the string when omitted.
3: When the parameter is a negative number, the incoming negative value will be processed and added to the length of the string.
illustrate
1: When the last parameter is omitted, intercept it to the end.
2: When the parameter is a negative number, its value is the length of the string + the negative number
3: Does not contain the parameter itself
substring()
Note: The syntax and functions are exactly the same as slice()
The difference is that
1: When the parameter is a negative number, automatically convert the parameter to 0
substr()
grammar
stringObject.substr(start,len)
Function
Intercept substring
Parameter Description
1:start must specify the starting position of the substring
2: len is optional and represents the length of the intercepted characters. If omitted, truncate to the end of the string.
3: When start is a negative number. Will process the incoming negative number and add it to the length of the string
4: When len is a negative number, return an empty string
Learning Objectives Two methods split() replace() in String
split()
replace()
split()
grammar
stringObject.split(separator)
Function
Split a string into an array of strings
Return valueArray
illustrate:
separator required, separator
replace()
grammar
stringObject.replace(regexp/substr,replacement)
Function
Replace some characters with other characters in a string, or replace a substring that matches a regular expression
Return valueString
parameter:
regexp: a RegExp object that must specify the substring or pattern to be replaced
repalcement: required. a string value
String
Other ways to master string methods
toUpperCase()
toLowerCase()
3: Convert the string broder-left-color to border-LeftColor
toUpperCase() and toLowerCase()
grammar:
stringObject.toUpperCase()
Function: Convert string to uppercase
grammar
stringObject.toLowerCase()
Function: Convert string to lowercase
Math object
1: Master the methods of Math object
min()
max()
ceil()
floor()
round()
abs()
Math.min()
grammar
Math.min(num1,num2,...numN)
Function:
Find the minimum value of a set of numbers
Return value: Number
Math.max()
grammar
Math.max(num1,num2,..numN)
Function
Find the maximum value in a set of books
Return value: Number
Math.ceil()
grammar
Math.ceil(num)
Function
Rounded up
That is, return the smallest integer greater than num
Return value: Number
Math.floor()
grammar
Math.flor(num)
Function
Round down and return the integer part of num
Return value: Number
Math.round()
grammar
Math.round(num)
Function:
Round the value to the nearest frame number
Return value: Number
Math.abs()
grammar
Math.abs(num)
Function
Returns the absolute value of num
Return valueNumber
learning target
1: Master the random() method of Math object
2: Encapsulate a function that finds a random integer between n and m
Math.random()
grammar
Math.random()
Function
Returns a random number greater than or equal to 0 and less than 1
Return valueNumber
illustrate:
Find the formula for a random integer between n and m
random= Math.floor(Math.random()*(m-n+1)+n);
date object in javaScript
1: Master the method of creating date objects
2: Master the method of obtaining date and time in date object
3: Master the method of setting date and time in date object
How to create a date object
Syntax new Date()
Function: Create a datetime object
Return value: Returns the current date and time object without passing parameters.
How to get year, month, day, hour, minute, second and day of the week
1: getFullYear(): Returns the 4-digit year
2: getMonth(): Returns the month in the date, the return value is 0-11
3: getDate(): Returns the number of days in the month
4: getDay(): Returns the day of the week, return value 0-6
5: getHours() returns hours
6: getMinutes(): returns minutes
7: getSconds() returns seconds
8: getTime(): Returns the number of milliseconds representing the date
How to set year, month, day, hour, minute, second and day of the week
1: setFullYear(year) sets the four-digit year
2: setMonth(mon) sets the month in the date, starting from 0, 0 means January
3: setDate(): Set date
4: setDay() sets the day of the week, starting from 0, 0 represents the day of the week
5: setHours() sets hours
6: setMinutes() sets minutes
7: setSeconds() sets seconds
8: setTime() sets the date in milliseconds. will change the entire date
How to create a date object
Syntax; new Date()
Function: Create a datetime object
Return value: Returns the current date and time object without passing parameters.
illustrate
If you want to create a datetime object based on the date and time of the attribute, you must pass in the date representing the
The number of milliseconds or a set of comma-separated parameters representing the year, month, day, hour, minute and second
javaScriptDOM basics
The complete javaScript is provided by ECMAScript (grammar)
Browser Objects (DOM BOM) (property) composed of
1: How to get an element
2: How to access the style of an element
3: How to set and delete attributes
1: Master the basic DOM search methods
document.getElementByid()
document.getElementsByTagName()
2: Master how to style DOM elements
Syntax: document.getElementById("id")
Function: Returns a reference to the first object with the specified ID
Return value: DOM object
Description: id is the value of the id attribute on the DOM element
Syntax: docment.getElemetnsByTagName("tag")
Function: Returns a collection of all tag tag references in a team
Return value: array
Description: why tag needs to get the name of the tag
Set element style
Syntax: ele.style.styleNmae= styleValue
Function: Set the css style of the ele element
illustrate
1: ele is the style DOM object to be set
2: styleName is the name of the style to be set
3: styleValue is the set style value
learning target
1: Master the application of innerHTML attributes
2: Master the application of className attribute
3: Master how to add, delete and obtain attributes on DOM elements
Syntax: ele.innerHTMl
Function: Return the HTML between the opening and closing tags of the ele element
Syntax: ele.innerHTML= "html"
Function: Set the HTML content before the opening and closing tags of the ele element to html
innerHTML: Get and set the text and html content between tags
className
Syntax: ele.className
Function: Returns the class attribute of the ele element
Syntax: ele.className = "cls"
Function: Set the class attribute of the ele element to cls
Get element
How to get DOM element attributes or add attributes
Grammar: ele. getAttribute("attribute")
Function: Get the attribute attribute of the ele element
illustrate
1: ele is the dom object to be operated on
2: attribute is the html attribute to be obtained (such as: id, type)
Set properties
语法:ele.setAttribute("attribute",value)
Function: Set attributes on the ele element
illustrate
1: ele is the dom object to be operated on
2: attribute is the name of the attribute to be set
3: value is the value of the attribute attribute set
Delete attribute
Syntax: ele.reniveAttrubute("attribute")
Function: Delete the attribute attribute on ele
illustrate
1: ele is the dom object to be operated on
2: attribute is the name of the attribute to be deleted
javaScript basic events
learning target
1: Master what an event is
2: Master HTML events
3: Master DOM level 0 events
4: Master common mouse and keyboard events
5: Master the direction of this
HTML events
Add events directly within HTML element tags and execute scripts
Syntax <tag event="execute script</tag>
Function: Bind events on HTML elements
Note: Executing the script can be done by calling a function.
mouse events
- onload: triggered when the page loads
-onclick: Triggered when mouse clicks
-onmouseover: triggered when the mouse rolls over
-onmouseout: triggered when the mouse leaves
-onfoucs: triggered when focus is obtained
-onblur: triggered when focus is lost
-onchange: Occurs when the contents of the domain change
DOM0 level event
Syntax: ele.event = execute script
Function: Binding events on DOM objects
Note: The execution script can be an anonymous function or a function call
mouse events
-onsubmit: Occurs when the confirmation button in the form is clicked
-onmousedown: Fires when the mouse button is pressed on the element
-onmousemove: Occurs when the mouse pointer moves
-onmouseup: Triggered when the mouse button is released on the element
-onresize: triggered when the browser window is resized
-onscroll: triggered when the scroll bar is dragged
Keyboard events and keyCode attributes
onkeydown: Occurs when the user presses a keyboard key
onkeypress: Occurs when a key is pressed and released on the keyboard
onkeyup: Occurs when a keyboard key is released
keyCode: Returns the value of the key triggered by the onkeypress onkeydown or onkeyup event
character code, or key code
javaScriptBOM basics
BOM (browser object model) browser object model
Objects in BOM
window
navigator
screen
history
location
document
event
Window is an instance of a browser. In a browser, the window object has dual roles.
Is it an interface for javaScript to access the browser window? Is there anything wrong with ECMSScript?
The specified Global object
All global variables and global methods are assigned to window
Syntax window.alert("content")
Function: Displays an alert box with a message and a confirmation button
Syntax: window.confirm("message");
Function: Display a dialog box with a specified message and OK and Cancel buttons
Syntax: window.prompt("text","defaulttext");
Parameter Description:
text: Plain text displayed in the dialog box (not HTML-formatted text)
defaultText: default input text
Return value: If the customer clicks the cancel button of the prompt box, null is returned
Returns the text that the input field safely displays if the customer clicks the confirm button
window object
Syntax: window.open(pageURL,name,parameters)
Function: Open a new browser window or find a named window
Parameter Description:
pageURL: child window path
name: sub-window handle (name declares the name of the new window, which facilitates the later reference of the sub-window by name)
parameters: window parameters (each parameter is separated by commas)
Syntax window.close()
Function: Close browser window
The method of the window object-timer
1: Master timeout calls
2: Master intermittent calls
JavaScript is a single-threaded language. Single-threading means that the executed code must be executed in order.
Syntax: setTimeout(code, millisec)
Function: Call a function or calculated expression after a specified number of milliseconds
Parameter Description
1: code: The function to be called or the javaScript code string to be executed
2: millisec: the number of milliseconds to wait before executing the code
clear timeout call
Syntax clearTimeout(id_of_settimeout)
Function: Cancel the timeout set by the setTimeout() method
Parameter Description:
1:id_of_settimeout: The ID value returned by setTimeout(), which identifies the delayed execution code block to be canceled
intermittent call
Syntax setInterval(code,millisec)
Function: Execute code every specified time
Parameter Description:
1: code: The function to be called or the code block to be executed
2: millsec: The time interval between periodic execution or calling code is calculated in milliseconds.
Syntax: clearInterval(id_of_setinterval)
Function: Cancel the interval set by the setIntreval() method
Parameter description:
1:id_of_setinterval: id value returned by setInterval ()
localtion
1: Master the location object
2: Master the common attributes of location objects
The location object provides information about the document loaded in the current window and also provides some navigation
function, it is both a property of the window object and a property of the docuemnt object
Common properties of location objects
Syntax: location.href
Function: Return the complete URL of the currently loaded page
Note: location.href is equivalent to window.location.href
Syntax: location.hash
Function: Return the hash in the URL (# followed by zero or more characters), if it does not contain the hash, return empty
Syntax: location.host
Function: Return server name and port number (if available)
Syntax: location.hostname
Function: Return the server name without port number
Syntax: location.pathname
Function: Return the directory and/or file name in the URL
Syntax: location.port
Function: Return the port number specified in the URL, if not, return an empty string
Syntax: location.protocol
Function: Return the protocol used on the lunar surface
Syntax: location.search
Function: Returns the query string of the URL. This string starts with a question mark.
1: Master position operations
2: Master location.reaplace()
3: Master location.reload()
How to change browser location
location.href property
Other attributes of the location object can also change the URL
location.hash
location.search
Syntax: location.replace(url)
Function: Redirect URL
Note: Using location.replace will not generate new records in the history.
location.reload()
Syntax: location.reload()
Function: Reload the currently displayed page
illustrate
location.repoad() may load from cache
location.reload(true) reloads from the server
Master the history object in BOM
Syntax: history.back()
Function: Go back to the previous step in history
Note: Equivalent to using history.go(-1)
Syntax: location.forward()
Function: Go back to the next step in history
Note: Equivalent to using history.go(1)
1: Master the Screen object and its common properties
Syntax: screen.availWidth
Function: Returns available screen width
Syntax: screen.availHeight
Function: Return available screen height
To get the height and width of the window document display area, you can use innerHeight and innerWidth
To get the height and width of the display screen, you can use availHeght and availWidth
Navigator object
1: Master the userAgent attribute of the Navigator object
2: Master how to determine the browser type
3: Master how to determine whether the device’s terminal is mobile or PC
UserAgent: Used to identify browser name, version, engine, operating system and other information and content
Learning Content
1: Front-end development process and use of necessary tools
2: HTML5 tags, tag structure, BEM development model
3: css3 css transition animation frame animation
4: Acquisition of js elements and processing of event responses
Extension: Front-end development process
1: Need analysis
2: Visual design, interactive animation design
3: Front-end static page development and animation effect development
Related tools
1: Editor Sublime3
2: Annotation tool PxCook
3: Cutting tool: PhotoShop
Development Process
1: mark
2: Sprite image GoPng
Development skills
1: From big to small
2: BEM development model
BEM stands for Blick Element Modifier
Summary of centering methods
1: Text is centered vertically
2: The block element is vertically centered with the parent element
3: The block element (container) is centered horizontally