console.log (a); // First use the variable var a = 12; // Then define the variable
The basic data type
Number.
3e8
is 3^8
0b
, the octal starts with 0
, and the hexadecimal starts with 0x
.NaN
, not a number, that is, "not a number", but it is A value of numeric type (in mathematical operations, if the result cannot be a number, the result is often NaN, NaN == NaN, the result is false)String
function | charAt | |
---|---|---|
() | gets the specified position character (out of bounds | )is an empty string) |
substring() | extracts the substring | |
substr() | extracts the string | |
slice() | extracts the substring | |
toUpperCase() | changes the string to uppercase | |
toLowerCase() | changes the string to lowercase | |
indexOf() | retrieves the string (pattern matching) |
Boolean
Undefined
Null.
Complex data types:
can be used to detect values or variables. Type
typeof 5; // numbertypeof 'niubi'; // string
type name | typeof detection result | value example |
---|---|---|
number type | number | 5 |
type | string | 'niubi' |
Boolean type | boolean | true |
undefined | undefined | undefined |
null type | object | null |
uses **Number ()**Function
// String --> Number Number('123'); // 123Number('123.4'); // 123.4Number('123 year'); // NaNNumber('2e3'); / / 2000Number(''); // 0Number('1 + 1'); // NaN// Boolean value --> Number(true); // 1Number(false); // 0// undefined and null - -> Number Number(undefined); // NaNNumber(null); // 0
**parseInt()** function converts a string to an integer
and will automatically truncate all characters after the first non-numeric character
parseInt('3.14 '); // 3parseInt('3.14 is pi'); // 3parseInt('Pi is 3.14'); // NaNparseInt('3.99'); // 3
**parseFloat()** function converts the string to Floating point numbers
automatically truncate the first non-numeric character and all characters after the non-decimal point
parseFloat('3.14'); // 3.14parseFloat('3.14 is pi'); // 3.14parseFloat('Pi is 3.14'); / / NaNparseFloat('3.99'); // 3.99// will automatically convert true and false into strings, and the result is NaN.
The **String()** function
becomes a "same-length" string. Scientific notation and non-decimal numbers will be converted to decimal values
String(123); // '123'String(123.4); // '123.4'String(2e3); // '2000'String(NaN ); // 'NaN'String(Infinity); // 'Infinity'String(0xf); // '15'String(true); // 'true'String(false); // 'false'String(undefined ); // 'undefined'String(null); // 'null'
**Boolean()** function
// Numbers --> Boolean values 0 and NaN are converted to false, and others are converted to trueBoolean(123); // trueBoolean(0); // falseBoolean(NaN); // falseBoolean(Infinity); // trueBoolean(-Infinity); // true// Boolean value --> Boolean empty string is converted to false, and other values are converted to true; Boolean(''); // falseBoolean('abc'); // trueBoolean('false'); // true// undefined and null --> Boolean value is converted to falseBoolean(undefined); // falseBoolean(null) ; // false
**prompt()** function pops up the input box
var num = prompt('Please enter the first number'); // The return value is a string
if involved in mathematical operations If an operand is not a numeric type, JavaScript will automatically convert the operand to a numeric type.
The essence of implicit conversion is to internally call the Number() function
3 * '4' // 12true + true // 2false + 2 // 23 * '2 days' // NaN
Math.pow(2, 3) // 2^3Math.sqrt(81) // 9Math.ceil() // Round up Math.floor () // Rounding down
=== // All equal!== // Not all equal // Two equal signs == operator does not compare the type of the value, it will compare the value after implicit conversion Is it equal? 1 == true // true1===true // false0 == false // true0 === false // false0 == undefined // false0 === undefined // falseundefined == null // trueundefined == = null // false
**isNaN()** function determines whether the variable value is NaN,
but isNaN() is not easy to use. Its mechanism is: as long as the execution result of the variable passed into Number() is NaN, then isNaN( ) function will get true
a && ba is true, the value is b; a is false, the value is a
a||ba is true, the value is a, a is false, the value is b
Logical operation priority : non--> and- -> Or
comprehensive operation operation sequence : non--> Mathematical operation --> Relational operation --> Logical operation
Random number function Math.random()
obtains an integer in the interval [a, b], the formula is parseInt(Math .random() * (b - a + 1)) + a;
var arr = ['A', 'B', 'C', 'D']; var arr = new Array('A', 'B ', 'C', 'D');var arr = new Array(4); An array of length 4, each item is undefined.
When the subscript is accessed out of bounds, undefined is returned.
var arr = [2, 6, 7, 3 ];arr[6] = 4;console.log(arr); At this time, the subscript is out of bounds, no error will be reported, but the array will be expanded, subscript 6 is 4, and the middle is emptyArray.isArray() method can be used To detect array
function definition
// regular function fun() { //Function body statement}//Anonymous function var fun = function () { // Function body statement}
Promotion of function declaration
fun(); function fun() { // Will be promoted in the pre-parsing stage alert("Function is executed");}// If the function is defined with a function expression , there is no promotion feature fun(); // an error is raised var fun = function () { alert("Function is executed");}
Function priority promotion
// Function priority promotion // Promotion after function expression; variable declaration promotion, cannot override the promoted function fun(); // Pop up Bvar fun = function () { alert('A');}function fun() { alert('B');}fun(); // Pop up A.
The actual number of formal parameters is different.
undefined
arguments array object
The var declaration and omission
are outside the function. The variables declared with var are global variables, and the variables declared without var are global variables
in the function. , variables declared with var are local variables, variables declared without var are global variables
, both are global variables, and both are one of the attributes of the window object. Variables declared with var cannot be deleted, and variables declared without var can be deleted!
Return value
function sum(a, b) { return a + b;}var result = sum(3, 5); // The return value can be received by a variable.
If the function does not return a value, the result printed on it is undefined.
sort(a, b) method
a in this function , b represent the front and back items in the array respectively. If they need to be swapped, any positive number is returned; otherwise, a negative number is returned.
var arr = [33, 22, 11, 55]; arr.sort(function ( a, b) { if (a > b) { return 1; } return -1;});
Variable assignment
For example, | when var a = b variable is passed a value | and == is used for comparison, | ||
---|---|---|---|---|
a new copy of | the basic type value | numeric, string, Boolean, and undefined | is generated in the memory.Whether the comparison value is equal or | |
not is | the reference type value | object or array. | Generate a new copy, but let the new variable point to the same object | to compare whether the memory address is the same, that is, compare whether it is the same object |
array deep clone
var arr1 = [1, 2, 3, [4, 5]]; function deepClone( arr) { var result = []; for (var i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) { result.push(deepClone(arr[i])); } else { result.push(arr[i]); } } return result;}
A local function
defined inside a function is a local function and
can only be called inside the function
fun() { function inner() { console.log('Hello'); } inner(); // Call the inner function} fun();
Scope chain
In the function nesting, the variable will look for its definition layer by layer from the inside to the outside
var a = 10; var b = 20; function fun() { var c = 30; function inner() { var a = 40; var d = 50; console.log(a, b, c, d); // When using variables, js will start from the current layer and look for definitions layer by layer} inner();}fun();
closure
closure is a combination of the function itself and the environment state in which the function was declared.
The function can "remember" the environment in which it was defined, even if the function is not in the environment in which it was defined. When called, you can also access the variables of the environment in which it was defined.
In js, a closure is created every time a function is created, but the closure feature often requires the function to be executed "in a different place" in order to be able to observe
the function of the closure. :
Memory: When a closure is generated, the state of the environment where the function is located will always be kept in memory and will not be automatically cleared after the outer function is called.
function fun() { var name = 'niubi'; function innerFun() { alert(name); } return innerFun;}var inn = fun();inn(); // The internal function has been moved to the external executionto simulate the private variable
function fun() { var a = 0; return function() { alert(a); }}var getA = fun();getA();function fun() { var a = 0; return { getA: function () { return a; }, add: function () { a++; }, pow: function () { a *= 2; } };}var obj = fun();console.log(obj.getA());obj.add();Note : Closures cannot be abused, otherwise it will cause performance problems on the web page, and in serious cases may lead to memory leaks.
Immediately call the function IIFE
special writing method. Once defined, the immediately called
function must be converted into a function expression before it can be called
(function () { // Turn the function into an expression through parentheses // statements})();+ function() { alert(1);}();-function() { alert(1);}();
can be used to assign values to variables
var age = 12; var sex = 'Male'; var title = (function () { if (age < 18) { return 'children'; } else { if (sex == 'male') { return 'Mr.'; } else { return 'Ms'; } }})();
In some situations (such as in a for loop), global variables are changed into local variables, and the syntax is more compact.
var arr = []; for (var i = 0; i < 5; i++) { arr.push(function () { alert(i); });}arr[2](); // Pop-up 5
solution:
var arr = [];for (var i = 0; i < 5; i++) { (function (i) { arr.push(function() { alert(i); }); })(i);}arr[2](); // Pop up 2
nodeType common attribute value
node nodeType attribute can display the specific type of this node
nodeType value | node type |
---|---|
1 | element node, for example and |
3 | text node |
8 | comment node |
9 | document node |
10 | DTD node |
The document object
accesses the element node mainly relying on the document object.
Almost all DOM functions are encapsulated into the document object.
The document object also represents the entire HTML document. It is the root of the DOM node tree.
Common methods
and | functions |
---|
document.getElementById() | gets the element through the id |
document.getElementsByTagName() | gets the element array through the tag name |
document.getElementsByClassName() | gets the element array through the class name |
document.querySelector() | gets the element through the selector |
document.querySelectorAll() | gets through the selector Element array |
document.getElementById()
If there are elements with the same id on the page, you can only get the first
<p id = "box">I am a box</p><p id = "para">I am a Paragraph</p>
var box = document.getElementById('box'); var para = document.getElementById('para');
The getElementsByTagName()
array is convenient for traversal, so that element nodes can be manipulated in batches
even if there is only one specified tag name on the page Node, you will also get an array with a length of 1.
Any node element can also call the getElementsByTagName() method to get the element node of a certain class inside it
<p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p><p>Paragraph</p>
var ps = document.getElementsByTagName('p');
getElementsByClassName()
<p class ="spec">Box</p><p class ="spec ">Box</p><p class = "spec">Box</p><p class = "spec">Box</p>
var spec_ps = document.getElementsByClassName('spec');
querySelector()
this method You can only get one element on the page. If there are multiple elements that meet the conditions, you can only get the first element
<p id = "box1"> <p>Paragraph</p> <p class = "spec">Paragraph</p> <p>Paragraph</p> <p>Paragraph</p></p>
var the_p = document.querySelector('#box1 .spec');
querySelectAll()
will get anarray
of length 1 even if there is only one node on the page that matches the selector.
To run,
use the window.onload = function() {} event (add an event listener to the window object, onload indicates that the page has been loaded), so that after the page is loaded, the specified code will be executed.
The relationship between nodes
will | consider all nodes | and only elements will be considered. Node |
---|---|---|
child node | childNodes | children |
parent node | parent node | same as |
first child node | firstChild | firstElementChild |
last child node | lastChild | lastElementChild |
previous sibling node | previousSibling | previousElementSibling |
next sibling node | nextSibling | nextElementSibling |
Note: Text nodes also belong to nodes, so we generally exclude text Node interference (using only element nodes)
to write common node relationship functions
<body> <p id = "box1"> <p>Paragraph</p> <p class = "spec">Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> </p> <script> var box = document.getElementById('box1'); var spec = document.getElementsByClassName('spec'); // Encapsulate a function that returns all child element nodes of the element, similar to children's function getChildren(node) { var children = []; // Traverse all child nodes of node and determine whether the nodeType attribute of each byte is 1 // If it is 1, push the result array for (var i = 0; i < node.childNodes.length; i++) { if (node.childNodes[i] == 1) { children.push(node.childNodes[i]); } } return children; } // Encapsulate a function that can return the previous element sibling node of the element, similar to previousElementSibling function getElementPrevSibling(node) { var o = node; while (o.previousSibling != null) { if (o.prebiousSibling.nodeType == 1) { // End the loop and find return o.previousSibling; } o = o.previousSibling; } return null; } // Encapsulate a function that can return all element sibling nodes of the element function getAllElementSibling(node) { var prevs = []; var nexts = []; var o = node; while (o.previousSibling != null) { if (o.previousSibling.nodeType == 1) { prevs.unshift(o.previousSibling); } o = o.previousSibling; } o = node; while (o.nextSibling != null) { if (o.nextSibling.nodeType == 1) { nexts.push(o.nextSibling); } o = o.nextSibling; } return prevs.concat(nexts); } </script></body>
Change the content in the element node.
You can use two related attributes to change the content in the element node.
innerHTML
can set the content in the node in HTML syntax.
innerText
can only set the content in the node in the form of plain text.
<body > <p id = "box"></p> <script> var oBox = document.getElementById('box'); oBox.innerHTML = '<ul><li>Milk</li><li>Coffee</li></ul>'; // Can parse HTML syntax // oBox.innerText = 'niub'; // Only Can be plain text</script></body>
Changing the CSS style of an element node
is equivalent to setting the inline style attribute
oBox.style.backgroundColor = 'red'; // CSS attributes should be written in camel case oBox.style.backgroundImage = ' url(images/1.jpg)';oBox.style.fontSize = '32px';
Change the HTML
attributes of element nodes to standard W3C attributes, such as src, href, etc., just click directly to make changes
oImg.src = ' images/2.jpg';
For attributes that do not comply with W3C standards, use setAttribute() and getAttribute() to set and read
<body> <p id = "box"></p> <script> var box = document.getElementById('box'); box.setAttribute('data-n', 10); // Add data-n attribute with a value of 10 var n = box.getAttribute('date-n'); alert(n); </script></body>
Node creation
document.createElement() method is used to create an HTML element with a specified tagname
var op = document.createElement('p');
ifThe newly created node is an "orphan node", and It is not mounted on the DOM tree and cannot be seen. You
must continue to use the appendChild() or insertBefore() method to insert the orphan node into the DOM tree.
Any node that is already on the DOM tree can call the appendChild() method, which can Mount the orphan node inside it and become its last child node
parent node.appendChild (orphan node);any node that is already on the DOM tree can call the insertBefore() method, which can mount the orphan node Go inside it and become the parent node of the node before its "benchmark child node"
.insertBefore(orphan node, benchmark node);
the mobile node
makes the node that has been mounted on the DOM tree become appendChild() or insertBefore() Parameters, this node will be moved to
new parent node.appendChild (node that already has a parent); new parent node.insertBefore (node that already has a parent, benchmark child node); // This means that a node cannot be located in the DOM tree at the same time
Delete nodes
in two locations.The removeChild() method deletes a child node
parent node
from the DOM.removeChild
(to delete the child node);the clone node
cloneNode() method can clone the node. The cloned node is an "orphan node".
The parameter is boolean. Type, indicating whether to use deep cloning. If true, all descendant nodes of the node will also be cloned. If false, only the node itself will be cloned.
var orphan node = old node.cloneNode(); var orphan node = old Node.cloneNode(true);
event
event name | event description |
---|---|
onclick | when the mouse is single on an object |
ondbclick | when the mouse double-clicks on an object |
onmousedown | when a mouse button is pressed on an object |
onmouseup | when a mouse The button is released on an object |
onmousemove | When a mouse button is moved on an object |
onmouseenter | When the mouse enters an object (similar event onmouseover) |
onmouseleave | When the mouse leaves an object (similar event onmouseout) |
onmouseenter does not bubble , onmouseover bubbling
event name | event description |
---|---|
onkeypress | when a keyboard key is pressed (system buttons such as arrow keys and function keys cannot be recognized) |
onkeydown | when a keyboard key is pressed (system buttons are Identified, and will take precedence over onkeypress) |
onkeyup | When a keyboard key is released |
event name | Event description |
---|---|
onchange | After the user changes the content of the field |
oninput | is modifying the content of the field (input content) |
onfocus | When an element is obtained focus (such as tab key or mouse click) |
onblur | when an element loses focus |
onsubmit | when the form is submitted |
onreset | when the form is reset |
event name | event description |
---|---|
onload | when the page or image is completed loading |
onunload | when the user exits the page |
when the box Execution order of event listening when nested
<p id = "box1"> <p id = "box2"> <p id = "box3"></p> </p></p><script> var oBox1 = document.getElementById('box1'); var oBox2 = document.getElementById('box2'); var oBox3 = document.getElementById('box3'); oBox1.onclick = function () { console.log('box1'); }; oBox2.onclick = function () { console.log('box2'); }; oBox3.onclick = function () { console.log('box3'); }; // Click the innermost box, the propagation direction is from inside to outside</script>
Event propagation
TheThe propagation of events is: first from the outside to the inside, and then from the inside to the outside (the innermost layer is not captured first and then bubbled, but is determined based on the order of writing code. Boxes with the same name are related to the same stage and order. If the same element is set If there are two or more events with the same name, the one written later in DOM0 level will overwrite the one written first; and DOM2 level will be executed in order)
onxxxx (DOM0 level event monitoring) can only monitor the bubbling stage, so the observed results are from Inside to outside
addEventListener() method (DOM level 2 event monitoring)
oBox.addEventListener('click', function() { // Here is the event processing function}, true); // If the third parameter is true, it will listen to the capture phase. If it is false, it will listen to the bubbling phase.
event object
event processing function provides a formal parameter, which is an object that encapsulates The details of this event
This parameter is usually represented by the word event or the letter e
oBox.onmousemove = function (e) { //Object e is the "event object" of this event};
Object related attributes
Attributes of the mouse position when this event is triggered Attribute
attribute | description |
---|---|
clientX | The horizontal coordinate of the mouse pointer relative to the browser |
clientY | The mouse pointer is relative to The vertical coordinate of the browser |
pageX | The horizontalcoordinate of the mouse pointer relative to the entire web page |
pageY | The vertical coordinate of the mouse pointer relative to the entire web page |
offsetX The horizontal coordinate of the mouse pointer relative to the event source | element |
offsetY | The vertical coordinate of the mouse pointer relative to the event source element |
The e.charCode attribute is usually used in the onkeypress event to represent the "character code" of the character entered by the user.
Character code number 0 ~ number 9 48 ~ 57 uppercase letter A ~ Z 65 ~ 90 lowercase letter a ~ z 97 ~ 122 The e.keyCode attribute is usually used in onkeydown and onkeyup events to represent the "keycode" of the key pressed by the user.
Key code number 0 ~ number 9 48 ~ 57 letter part uppercase and lowercase a ~ z 65 ~ 90 Four direction keys ← ↑ → ↓ 37, 38, 39, 40Enter key 13 Space key 32
Prevent the default event
e.preventDefault() method is used to prevent the "default action" generated by the event
e.stopPropagation() method is used to prevent Events continue to propagate
. Batch adding event listening performance issues.
Event Delegation.
Each event listening registration will consume a certain amount of system memory. , and adding events in batches will result in too many listeners and a large memory consumption (when there are a large number of similar elements that need to be added in batches, event delegation can reduce memory overhead). Use
the event bubbling mechanism to delegate events of descendant elements to
Note forancestor elements
: You cannot delegate non-bubbling events to ancestor elements.
When a dynamic element node is added to the tree, event delegation can be used to make the newly added elements to the tree have event listening
related
attributes | . Attribute description |
---|---|
target | The earliest element that triggered this event, that is "Event source element" |
currentTarget | The element to which the event handler is attached (this) |
The timer
setInterval() function can call a function repeatedly, with a fixed interval between each call
setInterval(function () { // This function will automatically be called at a fixed interval}, 2000); // The second parameter is the interval, in milliseconds // This function can receive the 3rd, 4th... parameters, and they will be passed in order Enter the function setInterval(function (a, b) { // The value of formal parameter a is 88, and the value of formal parameter b is 66}, 2000, 88, 66); // Starting from the third parameter, it represents the parameters passed into the function // Named functions can also be passed in setIntervalvar a = 0; function fun() { console.log(++a);};setInterval(fun, 1000);
Clear the timer
clearInterval() function can clear a timer
// Set the timer and use the timer variable to receive the timer var timer = setInterval(function ( ) { }, 2000);//When the button is clicked, clear the timer oBtn.onclick = function () { clearInterval(timer); };
The delayer
setTimeout() function can set a delayer. When the specified time is up, the function will be executed once and will not be executed repeatedly.
var timer = setTimeout(function () { // This function will be executed once after 2 seconds}, 2000); clearTimeout(timer); // Clear the delayer
asynchronously
: It will not block the CPU to continue executing other statements. When the asynchronous is completed, the "callback function" will be executed. (callback)
setInterval() and setTimeout() are two asynchronous statements
setTimeout(function () { console.log('A');}, 2000); // Asynchronous statement console.log('B'); // Asynchronous statement will not block the normal execution of the program // Running result BA
function throttles
the execution of a function once Finally, the second execution is allowed only after the execution cycle is greater than the set execution period.
var lock = true; function function that needs throttling () { // If the lock is closed, then if(!lock) will not be executed return; // Core statement of function // Lock lock = false; //Open the lock after the specified number of milliseconds setTimeout(function () { lock = true; }, 2000);}
The windowBOM (Browser Object Model, browser object model) is the interface for JS to interact with the browser window.
object
is the window in which the current js script is running, and this window contains the DOM structure, window The .document property is the document object.
In browsers with tab functionality, each tab has its own window object; that is, tabs in the same window will not share a window object.
Global variables will become window objects. The attribute
var a = 10; console.log(window.a == a); // true
This means that multiple js files share the global scope, that is, js files do not have scope isolation function.
Built-in functions are generally Window's methods
such as setInterval(), alert() and other built-in functions are generally window's methods
Window size related properties
Property | meaning |
---|---|
innerHeight | The height of the content area of the browser window, including horizontal scroll bars (if any) |
innerWidth | browser window The width of the content area, including vertical scroll bars (if any) |
outerHeight | The outer height of the browser window |
outerWidth | The outer width of the browser window |
To get the width of the window without scroll bars, use the document.documentElement.clientWidth
resize event
in the window After the size changes, the resize event will be triggered. You can use window.onresize or window.addEventListener('resize') to bind the event handler.
Thescroll height
window.scrollY property represents the pixel value of
document.documentElement
that has been scrolled in the vertical direction.The .scrollTop property also represents the window scroll height
. For better browser compatibility, the two are usually written together
var scrollTop = window.scrollY || document.documentElement.scrollTop;document.documentElement.scrollTop is not read-only, and window .scrollY is a read-only
scroll event.
After the window is scrolled, the scroll event will be triggered. You can use window.onscroll or window.addEventListener('scroll') to bind the event handler function
Navigator object.
The window.navigator property can retrieve the navigator. Object, which contains the relevant attributes and identification
attributes | of |
---|---|
appName | browser official name |
appVersion | browser version |
userAgent | browser user agent (containing kernel information and packaging shell information) |
platform | user operating system |
History object
window The .history object provides an interface for operating browser session history.
A common operation is to simulate the browser back button
history.back(); // Equivalent to clicking the browser's back button history.go(-1); // Equivalent to In history.back();
the Location object
window.location identifies the current URL. You can command the browser to jump to the page by assigning a value to this attribute
window.location = 'http://www.baidu.com';window.location. href = 'http://www.baidu.com';
To reload the current page,
you can call the reload method of location to reload the current page. The parameter true means that
window.location.reload(true) is forced to load from the server;
GET request query parameters
The window.location.search attribute is the current browser's GET request query parameter
offsetTops attribute.
This attribute indicates the vertical distance from this element to the positioned ancestor element.
Positioning ancestor elements: Among the ancestors, the element closest to itself and having a positioning attribute
Anuses this When adding attributes, all ancestor elements should not have positioning.
object (object) is a collection of "key-value pairs", which represents the mapping relationship between attributes and values.
var obj = { name: 'Xiao Ming', age: 12, sex: 'male', hobbies: ['football', 'programming']}; // Curly brackets in js represent objects.
Note:
If the object's attribute key name does not comply with the js identifier naming specification, the key name must be wrapped in quotes.
If the attribute name does not comply with js identifier naming convention, you must use square brackets to access.
If the attribute name is stored in the form of a variable, you must use square brackets in the form
var obj = { a: 1, b: 2, c: 3};var key = 'b';console.log(obj.key); // undefinedconsole.log(obj[key]); //
Creation of 2 objects
var obj = { a: 10};obj.b = 40;
Delete attributes.
Use the delete operator to delete the attributes of an object.
var obj = { a: 1, b: 2};delete obj.a;
Object method
If a property value is a function, it is called an object method
var xiaoming = { name: 'Xiao Ming', age: 12, sex: 'male', hobbies: ['football','swimming','programming'], 'favorite-book': 'Shuke and Beta', sayHello: function () { console.log('hello'); }};Traversing
an
object requires using a for...in...loop, but traversing each key of the object
for (var k in obj) { console.log('The value of 'attribute' + k + ' is' + obj[k]);}
Deep clone of object
var obj1 = { a: 1, b: 2, c: [33, 44, { m: 55, n: 66, p: [77, 88] }]};function DeepClone(o) { if (Array.isArray(o)) { var result = []; for (var i = 0; i < o.length; i++) { result.push(DeepClone(o[i])); } } else if(typeof o == 'object') { var result = {}; for (var k in o) { result[k] = DeepClone(o[k]); } } else { var result = o; } return result;}The this keyword can be used in the
context
function of the function. It means that the context of the function is
the same function. If it is called in different forms, the context of the function is different.
Only when the function is called can its context be determined.
Related
rules | Context |
---|---|
object. Function () | object |
function () | window |
array [下标]() | array |
IIFE | window |
timer | window |
DOM event processing function | binds DOM elements |
call and apply | any specified |
function. call (context); function. apply (context );
Difference:
function sum(b1, b2) { alert(this.c + this.m + this.e + b1 + b2);}sum.call(xiaoming, 5, 3); // Use commas to list the parameters of call sum.apply(xiaoming, [5, 3] ;
function fun() { // {} this points to this empty object this.a = 3; this.b = 5; // {a: 3, b: 5} // Automatically add return this;}var obj = new fun();console.log(obj);
The constructor
improves the previous function in a small step
function People(name, age, sex) { this.name = name; this.age = age; this.sex = sex;}var xiaoming = new People('小明', 12, 'male');var xiaoming = new People('小红', 10, 'female');var xiaogang = new People('小红' Gang', 13, 'Male');
and add the method
function People(name, age, sex) { this.name = name; this.age = age; this.sex = sex; this.sayHello = function () { console.log('I am' + this.name); };}var xiaoming = new People('Xiaoming', 12, 'male');xiaoming.sayHello();
prototype
Any function has a prototype attribute. prototype means "prototype" in English. The prototype attribute value is an object. It By default, the constructor attribute points back to the function
The prototype of the constructor is the prototype of the instance
prototype chain search
instance can access the properties and methods of its prototype. This is called a "prototype chain search"
function People(name, age, sex) { this.name = name; this.age = age; this.sex = sex;}People.prototype.nationality = 'China'; // Add the nationality attribute to the prototype of the constructor var xiaoming = new People('Xiao Ming', 12, 'Male'); console.log(xiaoming .nationality);
hasOwnProperty()
This method can check whether the object really "owns" a certain property or method
xiaoming.hasOwnProperty('name'); // truexiaoming.hasOwnProperty('age'); // truexiaoming.hasOwnProperty('sex'); / / truexiaoming.hasOwnProperty('nationality'); // false
in
The in operator can only check whether a property or method can be accessed by the object, but cannot check whether it is its own property or method
'name' in xiaoming // true'age 'in xiaoming // true's' in xiaoming // true'nationality' in xiaoming // True
adding a method to the method
to add the method to the instance body: the method function of each instance and each instance is memory. Different functions have caused waste of memory. You can write the method by writing the method.
function people (name, age, sex) { this.name = name; this.age = age; this.Sex = sex;} people.prototype.sayhello = Function () {{) console.log ('I am' + this.name);}; var xiaoming = new people ('Xiao Ming', 12, 'Man'); xiaoming.Sayhello ();
the end point of the prototype chain
;Array prototype chain
Inheritance
to inheritthe inheritance of the Prototype attribute to the parent class
The problem of inheriting the inheritance through the primary chain
. To solve the problem of the problem of the problem of reference type values and the problem of non -elegance of the subclass constructor in the prototype, it is usually used. Known as the "forgery object" or "classic inheritance"
in the internal constructor of the superclass in the subclass constructor, it should be paid attention to using call () to bind the context of the context of
the FUNCTION PeOPLE (name, sex, Age) { this.name = name; this.sex = sex; this.age = age; this.arr = [1, 2, 3];} Function Student (name, Sex, Age, SCHOOL, SID) { Peical.call (this, name, sex, age); this.school = SCHOOL '; this.sid = sign;} var xiaoming = New Student ('Xiaoming', 'Male', 12, 'School', 123456);
will be combined with the technology of the original chain and the technology of the constructor. Also called pseudo -classic inheritance
shortcomings:
The biggest problem of the combination inheritance is that under what circumstances, the constructor of two superclass is called: when creating a sub -class prototype, the other is inside the subclass constructor.
The prototype inherit
the object.create () method, you can create a new object (IE9) var obj2 = object.create (obj1) based on the specified object (
IE9); // Writing 2var obj2 = object.create (obj1, {// No. 1 No. 1 Two parameters are one object, and the value to be supplemented in inside D: {// The value of the attribute is still a object Value: 99 // } // Can cover the attributes of the same name on the prototype});;
There is no need to create a creation function of the creation of "promoting the masters", but just if the new object is "similar" to the existing object, use object.create () to
be competent. Sexual writing
realizes object.create ()// a function written by Douglas Crockford
in the low version of the browser.
// Create a temporary constructor function f () {} // Let the prototype of this temporary constructor point to O, so that the object of its new out, __ Proto__ point to O F.prototype = o; Return new f ();}
Parasitic inheritance and editor
to write a function that can "enhance the object", as long as the object is passed into this function, this function will use this object to create a new object as a "foundation" and give new objects to new objects new objects new objects are given new objects new objects new objects are given new objects new objects. The preset method
function f (o) { var p = object.create (o); p.display = function () { console.log (111); } Return p;}
Disadvantages:
Reduced efficiency because the function is not available (the method is not written on the prototype)
parasitic combination inheritance inheritance
the attribute by borrowing the constructor to inherit the attribute, and inherit the method of
the Function InheritProtype (Subtype, SuperType) { var prototype = object.create (supertype.prototype); subtype.prototype = prototype; } // Fundable people (name, sex, Age) { this.name = name; this.sex = sex; this.age = age; } Peical.prototype.sayhello = Function () { console.log ("Hello"); } Peical.prototype.sleep = Function () { console.log ("Sleep"); } // The subclass Function Student (name, Sex, Age, SCHOOL, SID) { Peical.call (this, name, sex, age); this.school = SCHOOL; this.sid = sign; } InheritPrototype (Student, PeOPLE); // Let the prototype of the Student class point to a new object student.prototype.exam = function () {{) {) { console.log ("exam"); }; var xiaoming = New Student ('Xiao Ming', 'Male', 12, 'School', 123456);
Instanceof operator is
used to detect the instance of a certain class "
xiaoming InstanceOf Student // Underground mechanism: Check the Student.prototype attribute on the prototype chain of xiaoming (how many layers are, as long as you can)
built -in constructor
JavaScript has a lot of endococcus constructor. For example, Array is a constructor of an array type. Function is the constructor of the function type
. On the prototype of the function, we can add a new method to this object to expand certain types of functions
Object.prototypeof the built -in constructor
is the end point of the original chain of all things, and the function array in the JavaScript is the object.
The purpose ofAny function can be regarded as a function "new". Object is a function, so it is also an object of the Function class
packaging and
packaging is to allow the basic type value to obtain method
Math.pow
() Math.sqrt () Math.ceil () // Take up math.floor () // Try math.round () // four house five into math.max () // The maximum value math.min () of the parameter list list // Calculate the maximum value of the ARR array var aRR = [3, 6, 9, 2]; var max = math.max.apply (null, arr);
Date objects
new date () // get the date object of the current time NewDate (2020, 11, 1) // 2020-12-01 ')
Common method
and method | function function |
---|---|
GetDate () | gets 1 ~ 31 |
getday () | to get 0 ~ 6 |
getmonth () | from 0 ~ 11 |
getfullyear () | to get the year |
gethouse () | get 0 ~ 23 getminutes 0 ~ 23 |
getminutes () | Get the number of minutes 0 ~ 59 |
getSeconds () | to get 0 ~ 59 timestamps of 0 ~ 59 |
time
stampsthrough
the gettime () method or date.parse () function.
Transform the timestamp to date object
var d = new date (); var timeStamp1 = d.gettime (); var timeStamp2 = date.parse (d);
regular
expression (regular expression) describes the "" Constitutional mode ", often used to check whether the string meets the predetermined format requirements to create regular expressions
/内容/
grammar formVAR Str = '123456'; var regXP =/^{6} $/; if (if (if (if (if (if (if (if (if (if (if (if (if (if (if (if (if (if (if regXP.Text (STR)) { alert ('Follow the rules');} else { Alert ('Not in line with the rules');}
VAR RegXP2 = New Regexp ('^\ D {6} $')
Yuan
character | function |
---|---|
d | matching a number |
d | matching one Non -digital characters |
W | match |
a | single character (letters, numbers, or downline) |
W | match non -single characters |
s | matching |
a | blank character, including space, formula and |
changing | lines |
. Whether there is a special significance, you can add a
before it to ensure that it expresses
the square
brackets of the symbol itself, such as [xyz], you can create a character set, indicating any character in the formula bracket bracket
/^[by] d {7} $/
Use a short horizontal -
to specify a character range, ^
It indicates that
character equivalent of the square | bracket representation |
---|---|
d | [0-9] |
d | [^0-9] |
w | [az-z0-9_] |
w | [^az-z0-9_] |
quantifier
and quantifier | meaning |
---|---|
* | match the previous expression 0 or multiple times. The equivalent at {0,} |
+ | match the previous expression once or multiple times. The equivalent at {1,} |
? | Match the previous expression 0 or 1 times. The equivalent at {0,1} |
{n} | matches the previous characters just N times |
{n,} | match the previous characters at least n times |
{n, m} | match the previous characters at least n times, up to M times M times, up to M times of M times, at most M times |
The modifier
is also called flags, which is used to use regular expressions to realize
the significance | of |
---|---|
high | -level |
search | modifiers |
. ');Introduction to
regular expression related methods
and | methods |
---|---|
test () | test whether a string matches regular expression, return to Boolean |
EXEC () | according to the regular expression, find in the string, return the result array or NULL |
string related related
Introduction tothe regular method and
method | search |
---|---|
() | in the string to find the matching according to the regular expression, return the first matching position index, return to -1 |
match () | to find the matching according to the regular expression in the string, return to the back, return to the return, and return to return, return In a array, if you ca n’t find it, return the null |
replace () | to replace the matching sub -string with replacement string. You can use a regular expression |
Split () | to separate the string as an array |
. ; // Search () method, much like indexof (), return the first bid to the found, if you can't find it -1 var result1 = str.search (/ d+/g); var result2 = str.search (/m/g); console.log (result1); // 3 console.log (result2); // -1 // MATCH () method, return the array you found, you can't find it if you can't find it var result3 = str.match (/ d+/g); console.log (result3); // ["123", "4567", "89"] // The replace () method is replaced with var result4 = str.replace (/[az]+/g, '*'); // Note+indicate greedy, as much as possible to match the lowercase letter console.log (result4 ); //*123*4567*89 // Split () method, disassemble the string into an array varress5 = str.split (/ d+/g); console.log (result5); // ["abc", "def", "gHi", ""]