JS array type conversion summary

[Basic data types]

  • The number of digital
  • String string
  • Boolean Boolean
  • Null null
  • Undefined undefined

[Reference data type]

  • The object type
    • Ordinary objects
    • Array objects
    • Regular objects (RegExps)
    • Math Object (Math)
    • Date function
  • The function function

Convert other data types to number

1. What happens

  • When isNaN detects: When detecting a value that is not a Number, the browser itself calls the Number method to convert it to a Number and then checks for an invalid Number
isNaN('3') = >false
Number('3') - >3
isNaN(3) - >false
Copy the code
  • Based on the parseInt parseFloat/Number is converted to a digital type to manually
  • Math: + – * / %, but “+” is not just math, it may also be string concatenation
'3'- 1= >2
Number('3') - >3
3- 1=2

'3px'- 1= >NaN

'3px'+1= >'3px1'String splicingvar i='3';
i=i+1; = >'and'
i+=1; = >'and'i++; = >4I++ is pure math and has abandoned the rule of string concatenationCopy the code
  • Other values are sometimes converted to numeric types when comparing based on “==”

2. Transformation rules

//=> The browser uses the Number() method by defaultWhenever an invalid numeric character is encountered, the result isNaN
' '->0
' '->0(Empty string with Spaces)'\n' ->0Newline character (Enter)'\t' ->0Tab [convert a Boolean to a number]true ->1
false ->0【 Convert nothing to numbers 】null ->0
undefined ->NaNAll values are first converted to a string (toString) and then converted to a number (toString).Number)
Copy the code

Converts values of other types to strings

1. What happens

  • Based on alert/confirm/prompt/document. The write method such as output, the output value is converted to a string, and then output
alert(1) = >'1'
Copy the code
  • String concatenation based on “+”
  • When a reference type value is converted to a number, it is first converted to a string and then to a number
  • Set an attribute name to an object. If it is not a string, convert it to a string and then store it in the object as an attribute (the attributes of the object can only be numbers or strings).
  • Manually call the toString/toFixed/join/String method, also is to convert a String
var a=Math.PI;
Math.PI.toFixed(2) - >'3.14'

var ary=[1.45.2.34.34];
ary.join("+")
'45 + 2 + 1 + 34 + 34';// Return the value of the original array unchanged

Copy the code

2. Transformation rules

//=> Call the toString methodExcept for the object, it is the result of your understanding of the transformation.1 ->'1'
NaN ->'NaN'
null ->null[] - >' '
[12] - >'12'
[12.23] - >'12,【 object 】 {name:"zhufneg".age:9} - >'[object Object]'{} - >'[object Object]'

Copy the code

Converts other values to Boolean types

1. What happens

  • Based on! /!!!!! /Boolean, etc
  • Conditions in a conditional judgment are eventually converted to a Boolean type
  • .
if(n){
	//=> Convert the value of n to Boolean to verify the condition
}

if('3px'+3) {//=> select * from '3px3' where ('3px3')
}
Copy the code

0/NaN/””/null/undefined 5 values are converted to Boolean false, the rest are converted to true

Special cases: mathematical operations and string concatenation

//=> String concatenation occurs when a string is present in the expression, otherwise it is a mathematical operation

1+true //=>2 Math operation
'1'+true  //=>'1true' string concatenation

[12] +10  //=>'1210' ('1210', '1210', '1210', '1210'({}) +10 //=>'[object Object]10'[] +10  / / = > '10'{} +10= >10{} represents a code block (block-level scope) +10{}; +10; (+10Is equivalent to0+10)

Copy the code

To consider

12+true+false+null+undefined+ + []'wy'+null+undefined+ + []true //=>'NaNwynullundefinedtrue'
Copy the code

Special case: “==” In comparison, if the data types on the left and right sides are different, convert them to the same type before comparison

Object == object: not necessarily equal, because objects operate on reference addresses, different addresses are not equal

{name:"xxx"} = = {name:"xxx"} [] = = = > []false

var obj1={};
var obj2=obj1;
obj1=obj2= >true
Copy the code

Object == number: Convert objects to numbers and then compare

Object == Boolean: Converts objects to numbers and booleans to numbers

Object == string: Converts an object to a string

[] = =' ' //->true
[12.23] = ='12, -//>true, if the object is converted to a number and both sides are NaN, then the result should be false
Copy the code

String == number: string to number String == Boolean: all to number Boolean == number: Converts a Boolean to a number

Rule:

1. Comparisons in different cases are made by converting other values into numbers and then making comparisons

2. When objects are compared to objects, they are compared to addresses

3, null = = undefined / / – > true

4, null === undefined ->false

Null, undefined, and other values are not equal

6, null = = null

7, undefined = = is undefined

8, null = = = null

9, undefined = = = is undefined

1= =true= >true
1= =false= >false
2= =true= >false[] = =true:falseAll converted to numbers0= =1! [] = =true:false[] = =false: trueAll converted to numbers0= =0! [] = =false: true! [] Convert the array to a Boolean type and invert itfalse= =false  
Copy the code

An analysis of the common methods of JS array

Arrays are also object data types and consist of key-value pairs

var ary = [12.23.34];
 /* * structure: * 0:12 * 1:23 * 2:34 * length:3 */
1.The index is incremented from zero with a number as the index (attribute name)2.There is a length property that stores the array length ary[0] get the first item ary[ary.length- 1] gets the last itemCopy the code

The value of each item in the array can be of any data type

//=> Multi-dimensional array
var ary=[
	{
		name:'xxx'.age:20
	}
	{
		name:'xxx'.age:20}]Copy the code

Common methods of arrays

Remember in four dimensions:

  • Function of method
  • Method parameters
  • Method return value
  • Whether the original array is changed

push

  • Grammar: ary. Push ()
  • Adds new content to the end of an array
  • Parameters: The content to append, can be one or more, can be various data types
  • Return value: The length of the new array
  • Original array change

pop

  • Grammar: ary. Pop ()
  • Deletes the last item at the end of an array
  • Parameters: no
  • Return value: The deleted item
  • The original array is changed

shift

  • Grammar: ary. The shift ()
  • Syntax: Deletes the first item in an array
  • Parameters: no
  • Return value: The deleted item
  • The original array is changed

unshift

  • Grammar: ary unshift ()
  • Adds new content to the beginning of an array
  • Parameters: The content to append, can be one or more, can be various data types
  • Return value: The length of the new array
  • Original array change

splice

delete

  • Grammar: ary. Splice (n, m)
  • Delete m entries from index N
  • Parameter: number of items to be deleted from the index
  • Return value: The deleted portion is returned with a new array
  • The original array is changed

increase

  • Grammar: ary. Splice (n, 0, x)
  • Delete zero items from index n and place x or more items in the array “before” index n
  • Parameter: index number of deleted items inserted
  • Return value: The deleted portion is returned with a new array
  • The original array is changed

Modify the

  • Grammar: ary. Splice (n, m, x)
  • Effect: Delete the original content, and then replace this part of information with new content
  • Parameter: index number of deleted items inserted
  • Return value: The deleted portion is returned with a new array
  • The original array is changed

All of the above methods are summarized

1. The way to append content to the front

  • Ary. Unshift (parameters)
  • Ary. Splice (0, 0, parameters)

2. Method of appending content at the end

  • Ary. Push (parameters)
  • Ary. Splice (ary. Length, 0, parameters)
  • Ary [ary. Length] = parameter

Delete the first item in the array

  • ary.shift()
  • Ary. Splice (0, 1)

Delete the last item in the array

  • ary.pop()
  • ary.splice(ary.length-1)
  • ary.length–

slice

  • Grammar: ary. Slice (n, m)
  • Cut from index n to index m (without m)
  • Return value: Stores the intercepted content in a new array
  • The original array doesn’t change

concat

  • Grammar: ary concat ()
  • Purpose: To concatenate multiple arrays (or values)
  • Parameters: arrays or values
  • Returns: a new array after concatenation
  • The original array stays the same

toString

  • Grammar: ary. ToString ()
  • Converts an array to a string
  • Parameters: no
  • Returns: a comma-separated string for each item in the array
  • The original array stays the same

join

  • Grammar: ary. The join ()
  • Function: Like toString, we convert an array to a string, but we can set the concatenation between each item when converted to a string
  • Parameter: Returns the specified link character
  • The original array stays the same

reverse

  • Grammar: ary. Reverse ()
  • Function: Arranges an array upside down
  • Parameters: no
  • Returns: a new sorted array
  • Original array change

sort

  • Grammar: ary. Sort ()
  • Sort an array
  • Parameters: none or callback function
  • Returns: new sorted array
  • Original array change

If no argument is passed: numbers up to 10 can be sorted in ascending order, but more than 10 can not be processed (multi-digit only identifies the first digit, sorted by the size of the first digit)

Ary. Sort (function(a,b){return a-b; }) descending: ary.sort(function(a,b){return b-a; })

Verifies that an array contains an item

indexOf && lastIndex0f

These two methods are incompatible with IE6-8

  • Syntax: ary.indexof(value to examine)
  • Gets the index of the first or last occurrence of the current item in the array
  • Parameter: The value to be detected
  • Return value: Index of the detected item
  • The original array stays the same

IndexOf returns an index greater than or equal to zero if there is an item in the array, and -1 if there is no item

//=> Verify that the array contains an item

if(ary.indexOf(100) >- 1) {//=>ARY contains 100 entries
}
Copy the code

Example: Array de-duplication scheme – indexOf method

Array.prototype.myUnique=function(){
	for(let i=0; i<this.length- 1; i++){let item=this[i],
			curary=this.slice(i+1);
		if(curary.indexOf(item)>- 1) {this[i]=this[this.length- 1];
			this.length--; i--; }}}Copy the code

Scheme two uses the uniqueness of object attribute names

Array.prototype.myUnique=function(){
	let obj={};
        for(var i=0; i<this.length; i++){if(typeof obj[this[i]]! = ='undefined') {this[i]=this[this.length- 1];
    		this.length--;
    		i--;
    		continues;
    	}
	obj[this[i]]=this[i];
    }
    obj=null;
}
Copy the code

Plan 3 uses double circulation


Array.prototype.myUnique=function(){
	for(var i=0; i<this.length- 1; i++;) {var item=this[i];
	for(var j=i+1; j<this.length; j++){if(item===this[j]){
			this[i]=this[this.length- 1];
			this.length--; j--; }}}}Copy the code

Scheme 4 adjacent division after sorting

Array.prototype.myUnique=function(){
	let ary=[];
	let _this=[...this];
	for(let i=0; i<_this.length; i++){let item=_this[i],
			nextItem=_this[i+1];
		if(item! ==nextItem[i+1]){ ary.push(item); }}return ary;
}
Copy the code

map

  • Grammar: ary. The map (function (item, index) {})
  • Parameter: function
  • Function: Iterates through each item in the array, executes the function once each time, and replaces the current item with the return value of the function. If the function returns no value, or there is no value after the return, then undefined is returned, and returns in a new array
  • Return value: New array after replacement
  • The original array stays the same
let ary=[12.23.34.25.36.47];
let curary=ary.map(function(item,index){
	return item+1;
});
console.log(curary);/ / = >,24,35,26,37,48 [13]
console.log(ary);/ / = >,23,34,25,36,47 [12]

----------------
let ary=[12.23.34.25.36.47];
let curary=ary.map(function(item,index){});console.log(curary);//=>[undefined,undefined,undefined,undefined,undefined,undefined]
Copy the code

Rewrite map method

Array.prototype.myMap = function myMap(callback, context) {
        var ary = [];
        if([].map){
            return this.map(callback,context);
        }
        for(var i=0; i<this.length; i++){var res = callback.call(context,this[i],i);
            ary.push(res);
        }
        return ary;

    }
Copy the code

filter

  • Grammar: ary. Filter (function (item, index) {})
  • Parameter: function
  • Filter an array and place the current items that meet the criteria into a new array
  • Return value: A new array that meets the criteria
  • The original array stays the same
let ary=[12.23.34.25.36.47];
let curary=ary.filter((item,index) = >{
	return item>20&&item<40;
})
console.log(curary);/ / = > [23,34,25,36]
Copy the code

find

  • Grammar: ary. Find (function (item, index) {})
  • Argument: callback function
  • Function: Filter array, return the current item that meets the condition for the first time
  • Return value: the item that meets the condition for the first time
  • The original array stays the same
let ary=[1.2.3.4.5];
let a=ary.find((item) = >{
    return item>1;
});
console.log(a);/ / = > 2
console.log(ary);/ / = > [1, 2, 3, 4, 5]
Copy the code

findIndex

  • Grammar: ary findIndex (function (item, index) {})
  • Argument: callback function
  • Function: Filter an array and return the index of the current item that meets the condition for the first time
  • Return value: The index of the current item that qualified for the first time
  • The original array stays the same
let ary=[1.2.3.4.5];
let a=ary.find((item) = >{
    return item>1;
});
console.log(a);/ / = > 1
console.log(ary);/ / = > [1, 2, 3, 4, 5]
Copy the code

some

  • Grammar: ary. Some (function (item, index) {});
  • Argument: callback function
  • The callback function executes several items in the array until it returns true
  • Return value: true or false, depending on what value follows the return (eventually converted to a Boolean type)
  • The original array stays the same
let ary=[1.2."string".NaN.3.4];
let a=ary.some((item) = >{
    console.log(item);/ / = > 1, 2, string
    return typeof item ==="string";
});
console.log(a);//=>true

---------------
let ary=[1.2."string".NaN.3.4];
let a=ary.some((item) = >{
    console.log(item);/ / = > 1, 2, string, NaN, 3, 4
    return 0;
});
console.log(a);/ / = > false, because the Boolean (0) = > false
Copy the code

every

  • Grammar: ary. Every ((item, index) = > {});
  • Argument: callback function
  • Function: Iterates through each item in the array, executes the callback function once, and stops iterating as soon as the result of the callback function returns false
  • Return value: true or false
  • The original array stays the same
let ary=[1.2.NaN.3.4];
let a=ary.every((item) = >{
    console.log(item);/ / = > 1, 2, NaN, 3, 4
    return typeof item==="number";
});
console.log(a);//=>true
------------
let ary=[1.2."string".NaN.3.4];
let a=ary.every((item) = >{
    console.log(item);/ / = > 1, 2, string
    return typeof item==="number";
});
console.log(a);//=>false
Copy the code

reduce

  • Grammar: ary. Reduce ((prev, item) = > {}, init).
  • Arguments: Callback functions (the first argument is the return structure of the previous callback function, and the second item is the current item), init represents the initial value passed to the function
  • Function: As an accumulator, each value in an array (reduced from left to right) evaluates to a value
  • Return value: The final result
  • The original array stays the same
let ary=[1.1.1.1.1.1.1.1.1.1];
let a=ary.reduce((prev,item) = >{
    console.log(prev, item);
    return prev-item;
},10);
console.log(a);//=>0
console.log(ary);/ / = >,1,1,1,1 [,1,1,1,1, 1, 1];
Copy the code

reduceRight

  • Grammar: ary. ReduceRight ((prev, item) = > {}, init)
  • Arguments: Callback functions (the first argument is the return structure of the previous callback function, and the second item is the current item), init represents the initial value passed to the function
  • Function: As an accumulator, each value in an array (reduced from right to left) evaluates to a value
  • Return value: The final result
  • The original array stays the same
let ary=[- 1.1.- 1.1];
let b=ary.reduceRight((prev,item) = >{
    console.log(prev, item);
    return prev*item;/ / = > 10 * 1 * 1 * 1 * 1
},10);
console.log(b);/ / = > 10
Copy the code

Some details about strings in JS

All strings enclosed in single or double quotation marks in JS are strings, and each string is composed of zero to more than one character

var str = 'zhufengpeixun'; Str. length -> string length STR [0] - >'z'
str[str.length- 1] - >'n'
str[100] - >undefined

//=> Each character in the string has its own index, as well as the length of an array to represent its own length

//=> Loop over the string, output each character
for(var i=0; i<str.length; i++){console.log(str[i]);
}
Copy the code

Common methods for strings

Strings are basic data types. Each operation on a string is a direct operation on a value, unlike an array, which is based on a spatial address. Therefore, there is no such thing as whether the original string is changed or not

charAt && charCodeAt

  • Syntax: str.charat (index)
  • CharCodeAt not only retrieves characters, but also retrieves their Unicode encoding values (ASCII).
  • Parameter: index
  • Return value: character or corresponding encoding

indexOf && lastIndexOf

Using these two methods, you can obtain the index of the first or last occurrence of a character in the string, return an index greater than or equal to zero if the character exists, and return -1 if the character does not exist. Therefore, you can use these two methods to verify whether the current string contains a character

var str = 'zhufengpeixun';
if(str.indexof(The '@') >- 1) {//=> The conditional statement contains the @ sign
}
Copy the code

slice

  • Grammar: STR. Slice (n, m)
  • Str.slice (n,m) starts at index n at index m (excluding m) and returns the found character as a new string
  • Return value: truncated string

substring

  • Grammar: STR. The substring (n, m)
  • STR. Substring (n,m) returns the character found as a new string from index n to index m.Negative numbers are not supported as indexes
  • Return value: truncated string

substr

  • Grammar: STR. Substr (n, m)
  • Function: Intercepts m characters from index n

toUpperCase && toLowerCase

  • Grammar: STR. ToUpperCase ()/STR. ToLowerCase ()
  • Role: to achieve letter case conversion
    • ToUpperCase converted from lowercase toUpperCase
    • ToLowerCase uppercase toLowerCase case
  • Parameters: no

split

  • Grammar: STR. The split ()
  • Split split split split the string into each item in the array according to the specified separator

replace

  • Syntax: str.replace(old character, new character to replace)
  • Function: Replaces existing characters in a string
  • Returns: the replaced string

Requirements in real projects

1. Format the time string

Requirement: there is a time string “2018-4-4 16:26:8”. We want to get “16:26 apr 04” based on this string

var str="The 2018-4-4 16:26:8",
    ary=str.split(' '),
	aryLeft=ary[0],
	aryRight=ary[1];
	month=aryLeft.split(The '-') [1],
	day=aryLeft.split(The '-') [2],
	hour=aryRight.split(':') [0],
	minute=aryRight.split(':') [1];

function fn(n){
	return n<10?"0"+n:n;
}
var date=fn(month)+'month'+fn(day)+'day'+fn(hour)+'when'+fn(minute)+'points'

console.log(date); -- -- -- -- -- -- -- -- -- -- -- -- -- -- regularlet reg=/^(\d{4})[-/](0? [1-9] | 1 [2-0]) [-] / (0? [1-9]|[12]\d|3[01])\s+(0? [1-9]|1\d|2[0-3]):(0? \d|[1-5]\d):(0[1-9]|[1-5]\d)$/;
console.log(reg.exec(str));
Copy the code

2. Address question mark parameter resolution

A URL “www.zhufengpeixun.cn/stu/?1x=1&n…” {1x:1, name:’AA’, sex:’man’}

var str="http://www.zhufengpeixun.cn/stu/?1x=1&name=AA&sex=man#teacher";
var indexASK=str.indexOf("?");
var indexWell=str.indexOf(The '#');

if(indexWell>- 1){
	str=str.substring(indexASK+1,indexWell);
}else{
	str=str.substr(indexASK+1);
	
}
var ary=str.split('&');
var obj={};
for(var i=0; i<ary.length; i++){var curary=ary[i].split('=');
	obj[curary[0]]=curary[1];
}

Copy the code

Example: Get the URL question mark and pass the parameter value - function encapsulation

function queryParameter(URL){
    var indexASK=URL.indexOf("?"),
        indexWell=URL.indexOf(The '#');
    indexWell>- 1? URL=URL.substring(indexASK+1,indexWell):URL=URL.substring(indexASk+1);
    var ary=URL.split('&'),
	    obj={};
    for(var i=0; i<ary.length; i++){var item=ary[i],
		    curary=item.split("=");
		    obj[curary[0]]=curary[1];
    }
    return obj;
}
Copy the code

Mathematical functions in JS

Math is called a mathematical function, but is of object type

typeof Math//=>'object'
Copy the code

They are called mathematical functions because the Math object provides many ways to manipulate numbers

Common methods provided in Math

abs

  • Grammar: Math. Abs ()
  • Action: Take absolute value

ceil && floor

  • Grammar: Math. Ceil ()
  • Action: Round up/down

round

  • Grammar: Math. The round ()
  • Action: Round

sqrt

  • Grammar: Math. SQRT ()
  • Action: Take the square root

pow

  • Grammar: Math. Pow (n, m)
  • Function: n to the m

max && min

  • Grammar: Math. Max ()
  • Function: Obtains the maximum or minimum value

PI

  • Grammar: Math. PI ()
  • Function: Get PI

random

  • Grammar: Math. The random ()
  • Gets the random decimal of [0,1]

Math.round(math.random ()*(m-n)+n)

Gets four random captcha - encapsulates the function

function queryCode(str){
    var result="";
    while(result.length<4) {var mathIndex=Math.round(Math.random()*(str.length- 1));
        result.indexOf(str.charAt(mathIndex))===- 1? result+=str.charAt(mathIndex):null;
    }
    return result;
}
queryCode();
Copy the code

function

function fn(n,m){//=> Parameter: entry
	/ / = > function body
	var total = 0;
	total=n+m;
	console.log(total)
}
fn(10.20);//=> Argument: the specific value passed to the parameter
/* * var a =12; * fn(a,1===1? 10:0); //=> The argument must be a value, even if we are writing a variable or expression, we pass the result of the evaluation of the variable or expression as a value to the parameter */
Copy the code

When a function is executed, a new private scope (private stack memory) is created to:

  • 1. Convert the string stored in the original heap memory into JS expression
  • 2. Protect private variables from external interference (and are isolated from the outside world). We call this protection mechanism of function execution, **” closure “**

function fn(n,m){
	var total=0; //=>total: private variable
	total=n+m;
}
fn(10.20);
console.log(total);//=>Uncaught ReferenceError: Total is not defined, total is a private variable, we cannot get this value directly outside the function (closure).
Copy the code

Return in a function

  • Entry to a function: parameter
  • Exit of the function: return value return
  • Take the result of a function’s execution (or part of the function’s body) outside the function for use
function fn(n,m){
	var total = 0;
	total = n+m;
	return total;//=> Returns the value stored in the total variable
}
fn //=> represents the function itself (the function itself is a value, which represents the code string in heap memory)
fn(10.20);//=> represents the function execution (not only that, it represents the result of the function execution, [return value])
Copy the code
function fn(n,m){
	var total = 0;
	total = n+m;
}
var res = fn(10.20);//=> If the current function does not return (or return; The function returns undefined on the outside
Copy the code
function fn(n,m){
	//=> If n/m has an unpassed value, we return zero
	if(n===undefined || m===undefined) {return 0;//=>return has another function: like a break in a loop, it forces the execution of code in the resulting function body (the code after return is not executed).
}
	var total=0;
	total=n+m;
	return total;
}
fn(10);//=> n=10,m = undefined,Number =>NaN,10+NaN=>NaN= = =1= = =1, n = = =undefinedThis is often the way to determine whether n is zeroundefinedThis way will do2, n = =undefinedIt's not a good model becausenull= =undefinedIs also equal (=== comparison is not equal)3,typeof n=='undefined'Developers on projects prefer this mode of judgment2= = =1, total =0; 0It has a value. It has a value0In memory terms, it takes up a place in stack memory2, total =null; Developers prefer to use itnullAs an initial value,nullIs an empty object pointer that takes up no memory;Copy the code

Arguments in functions

Parameters have limitations: we need to know exactly who the user is and how many arguments are passed at execution time, in what order, etc., before we can define the corresponding entry using parameters

Arguments: The built-in set of arguments to a function (built-in: the built-in mechanism for a function, whether you set parameters or pass arguments, arguments are there, always there)

function sum(){
	console.log(arguments);
}

Copy the code

Argument is an array of classes, not an array, and you can’t use the methods in the array directly

Even if parameter variables are set, what value should the parameter be, but arguments uses all arguments passed in, so it’s called a collection of arguments

function sum(){
	console.log(arguments.callee===sum);//=>true
}
Copy the code

Example: Sum of arbitrary numbers

//=> < span style = "max-width: 100%; clear: both; min-height: 1em

function sum(){
	var total=null;
	for(var i=0; i<arguments.length; i++){var item=arguments[i];
		if(!isNaN(Number(item))){ 
			total+=Number(item); }}return total;
}
Copy the code

Real-name and anonymous functions

  • Real-name function: having a function name
  • Anonymous function: without a function name
    • Function expression: An event that assigns a function as a value to a variable or element
    • Function (){function(){function(){… }) ();” However, statements that start with “function” are considered function declarations in JAVASCRIPT. Self-executing functions get a value, so you cannot write this directly. So start with an operator or parentheses ~func… Var a=function(){… } ();
=== Function expression ===var fn=function (){

}

oBox.onclick=function (){} === self-executing function (function (){}) ();//=> Since self-executing functions cannot start with function, function is preceded by the operator.

~function(){
		console.log(this)    //=>Window} ();/ / the return value is undefined ~ = > 1
	The binary no operator (~) changes each binary bit to the opposite value (0 to 1,1 to 0).
		
!function(){
		console.log(this)    //=>Window} ();/ / the return value is! undefined=>true
	
-function(){
		console.log(this)    //=>Window} ();/ / the return value is undefined - = > NaN

+function(){
			console.log(this)    //=>Window} ();/ / the return value is undefined = > NaN
	

Copy the code

DOM

The DOM tree

When a browser loads an HTML page, the first step is to calculate the DOM structure. The dom structure calculated is the DOM tree (the hierarchical relationship between HTML tags in the page is analyzed as a tree structure).

Method to get a DOM element

getElementById

Get the specified element object by the ID of the element, and we use document.getelementById (“”), where document limits the scope of the element, and we call it “context”.

The context of getElementById must be Document because the id of a page is strictly unique and the browser specifies that this unique ID can be obtained throughout the document

2, if the ID of the page is repeated, we can only get the first element based on this method

3. In IE6-7, the name attribute value of the form element (input) will be used as the ID.

getElementsByTagName

[context].getelementsByTagName Gets a collection of elements based on the tag name in the specified context (HTMLCollection)

1, access to the collection of elements is a class array (cannot directly use method of array) 2, it will be the current context, the children and grandchildren (offspring) tags within the hierarchy is available (3) to obtain the level is not only a son, and will always be based on the results of this method to obtain a collection (regardless of whether there is inside, and whether there are several, It is a container or collection), and if you want to operate on a specific item in the collection, you need to get it based on the index

Example: Search for all elements whose ID is HAHA

Get all the elements in the div with id = box, create an array of classes, iterate over each item in the array, and store it in the array if ID equals HAHA

The first option

<div class="box" id="box"> <ul> <li class="item1 item2"> News </li> <li class="item1"> </li> <li class="item2"> HAHA < / ul > < div id = "" name =" hobby "> latest news < / div > < div > latest movie < / div > < div id =" HAHA "> the latest music < / div > < / div > var OBox = document. GetElementById (' box '), nodeList. = oBox getElementsByTagName (' * '), ary = []; function queryAllById(id){ for(var i=0; i<nodeList; i++){ var item=nodeList[i]; item.id===id? ary.push(item):null; } return ary; }Copy the code

Second option

console.log(HAHA);
/ / = > HAHA for id name
Copy the code

In JS, the ID of an element is set to a variable by default (no need to retrieve the setting), and the ID is repeated. The result is a collection containing all ID items, or an element object (similar to the result obtained by ById).

getELementsByClassName

[context].getelementsbyClassName () Retrieves a collection of elements based on the element’s style class name (class=” XXX “) in the specified context

1. In real projects, we often style elements based on the style class, so in JS, we often get elements based on the style class, but this method is not compatible with IE6-8

Compatible processing scheme

Node.prototype.queryElementsByClassName = function queryElementsByClassName() {
    if (arguments.length === 0) return [];
    var strClass = arguments[0],
        nodeList = utils.toArray(this.getElementsByTagName(The '*'));
    strClass = strClass.replace(/^ +| +$/g.' ').split(/ +/);
    for (var i = 0; i < strClass.length; i++) {
        var reg = new RegExp('(^ | +)' + strClass[i] + '(+ | $)');
        for (var k = 0; k < nodeList.length; k++) {
            if(! reg.test(nodeList[k].className)) { nodeList.splice(k,1); k--; }}}return nodeList;
};
Copy the code

getElementsByName

Document. GetElementsByName () its context is the document, in the entire document, based on the element name attribute values for a set of nodes (and an array of classes)

1. In IE9 and below, only the name attribute of the form element is used. (Normally, the name attribute of the form element is only set in our project, and the name attribute of the non-form element is actually a non-standard operation.)

querySelector

[context].QuerySelector () retrieves the specified element object in the specified context based on a selector (similar to a CSS selector).

QuerySelectorAll > Based on querySelector, we get all the elements matched by the selector, and the result is a set of nodes (NodeList).

QuerySelector/querySelectorAll are not compatible with ie 6-8 browser

<div id="div1" class="fon mark" name="div1">01</div> <div id="div2" class="mark">02</div> <div id="div1" class="fon">03</div> <script> console.log(document.querySelectorAll("#div1")); / * * ID selector/console log (document. QuerySelectorAll (' mark ')); / * * class selector/console log (document. QuerySelectorAll (' body > div ')); / * child selector * / console log (document. QuerySelectorAll (' div ')); Tag selector / * * / console log (document. QuerySelectorAll (" body div ")); / * descendant selectors * / console log (document. QuerySelectorAll (" div [name = "div1"] ")); / * label attribute selectors * / console log (document. QuerySelectorAll (" * ")); /* wildcard selector */ </script>Copy the code

document.head

Get the head element object directly calls the head property on the document instance

document.body

The body element object directly fetches the body property on the document instance

document.documentElement

Fetches the documentElement property on the document instance

//=> Requirements: get the width and height of the browser screen (compatible with all browsers)

document.documentELement.clientWidth ||
document.body.clientWidth

document.documentELment.clien
tHeight ||
document.body.clientHeight
Copy the code

Node (node)

Everything that appears in an HTML document is a node

  • Element node (HTML tag)
  • Text nodes (text content, Spaces, line feeds)
  • Comment node (comment content)
  • Document node (Document)
  • .

Each type of node has attributes that distinguish it from its own characteristics and characteristics

  • NodeType: indicates the nodeType
  • NodeName: indicates the nodeName
  • NodeValue: nodeValue

Element nodes

  • NodeType: 1.
  • NodeName: indicates the uppercase label name
  • NodeValue: null

Text node

  • NodeType: 3
  • NodeName: “# text”
  • NodeValue: text content

Comment node

  • NodeType: 8
  • NodeName: “# comment”
  • NodeValue: comment content

A document node

  • NodeType: 9
  • NodeName: “# document”
  • NodeValue: null

Properties that describe relationships between nodes

parentNode

Gets the unique parent of the current node

childNodes

Gets all children of the current node

  • Child node: Only son level is obtained
  • All: contains element nodes, text nodes, and so on

children

In IE6-8, comment nodes are also retrieved as element nodes, so compatibility is not good

firstChild

Gets the first child of the current node (possibly an element or text)

firsrElementChild

The first element child node that gets the current node is not compatible in IE6-8

lastChild

Gets the last child of the current node (possibly an element or text)

lastElementChild

The child node that gets the last element of the current node is incompatible in IE6-8

previousSibling

Gets the last sibling of the current node (which could be an element, text, etc.)

previousElementSibling

Get the last elder element node (incompatible with IE6-8)

nextSibling

Gets the next sibling of the current node (which could be an element, text, etc.)

nextElemnentSibling

Get the next sibling element node (incompatible with IE6-8)

Compatibility processing 1-- Gets all element child nodes of the current element

Not compatible with lower versions of Internet Explorer based on Children (comments as element nodes)

// nodeType===1; // nodeType===1; // nodeType===1

/* *children:get all the element nodes of the current element *@parameter * curEle:[object] current element *@return * [Array] all the element nodes *by team on 2018/04/07 12:36 */
function children(curEle){
	var childEle=curEle.childNodes;
	var aryEle=[];
	for(var i=0; i<childEle.length; i++){var item=childEle[i];
		if(item.nodeType===1){ aryEle.push(item); }}return aryEle;
}

Copy the code

Compatibility process 2- Gets the last sibling element node of the current element

Incompatible with lower versions of IE browsers based on previousElementSibling

//=> find the elder node of the current element to see if it is an element node. If it is not, find the elder node based on the elder brother node. The search ends when the element node is found or there are no older brothers
/* *prev:get the last elder brother element node of the current element *@parameter * curEle:[object] current element *@return * [object] last elder brother element *by team on 2018/04/07 12:48 */
function prev(curEle){
   var item=curEle.previousSibling;
	   while(item && item.nodeType! = =1) {//=>item is used to verify that the current element is not present. If there is no item, it is null. Boolean(item)=>false
		   item=item.previousSibling;
	   }
	   return item;
}
Copy the code

Compatibility process 3- gets the next sibling node of the current item

NodeType ===1 nodeType== 1

/*
* next:get the next element of the current element
* @parameter:[object] the current element
* return:the next element
* by Fay on 17:58
*/
function next(curEle){
	var item=curEle.nextSibling;
	while(item && item.nodeType! = =1){
		item=item.nextSibling;
	}
	return item;
}
Copy the code

Compatibility process 4-- Gets all the sibling nodes of the current item

Create an empty array. If nodeType===1 is used for the sibling node of the current element, store it

/*
* nextAll:get all of the next elements by the current element
* @parameter:[object] the current element
* return: all of the next elements
* by Fay on 18:06
*/
function nexAll(curEle){
	var item=curEle.nextSibling,
		ary=[];
	while(item){
		item.nodeType===1? ary.push(item):null;
		item=item.nextSibling;
	}
	return ary;
}
Copy the code

Compatibility process 5- Gets all elder element nodes of the current item

/*
* preAll:get all of the previous elements by the current element;
* @parameter:[object] the current element
* return:[object] all of the previous elements
* by Fay on 18:11
*/
function preAll(curEle){
	var item=curEle.previousSibling,
		ary=[];
	while(item){
		item.nodeType===1? ary.push(item):null;
		item=item.previousSibling;
	}
	return ary;
}
Copy the code

Compatibility process 6-- Get all sibling element nodes of the current item

Add all sibling nodes to all sibling nodes

/*
* siblings:get all siblings elements by the current element
* @parameter:[object] the current element
* return:all siblings elements
* by Fay on 18:25
*/
function siblings(curEle){
	var preItem=curEle.previousSibling,
		nextItem=curEle.nextSibling,
		ary=[];
	while(preItem){
		preItem.nodeType===1? ary.push(preItem):null;
		preItem=preItem.previousSibling;
	}
	while(nextItem){
		nextItem.nodeType===1? ary.push(nextItem):null;
		nextItem=nextItem.nextSibling;
	}
	return ary;
}
Copy the code

Compatibility process 7-- Get the index of the current item

The index is the number of sibling nodes for the current element

/* * index:get the index of the current element * @parameter:[object] the current element * return:[number] the index of  the current element * by Fay on 18:17 */
function index(curEle){
	var item=curEle.previousSibling,
		ary=[];
	while(item){
		ary.push(item);
		item=item.previousSibling;
	}
	return ary.length;
}
Copy the code

Add, delete and change DOM

createElement

Create an element tag (element object) document.createElement ([tag name]) Document.createElement ([tag name]) A property on the document prototype

Example: Quickly get a queryURLParameter by dynamically creating an element

The A element has some built-in attributes:

  • Hash: stores the hash value ‘#teacher’
  • Search: question mark pass parameter value, no pass is empty string ‘? name=bd&age=10’
  • The hostname: domain name ‘www.baidu.cn’
  • The pathname: path ‘/ stu/’
function queryURLParameter(url){
var link=document.createElement('a');
link.href=url;
var search=link.search;
if(search.length===0) return;
   url=search.substr(1);
   var ary=url.split('&'),
    obj={};
for(var i=0; i<ary.length; i++){var curary=ary[i].split('=');
	obj[curary[0]]=curary[1];
}
	link=null
	return obj;
}
Copy the code

appendChild

Inserts an element object at the end of the specified container

[container].appendChild([newELe])

Properties on the Node class prototype whose values are functions

var newP = document.createElement('p');
document.body.appendChild(newP);
newP.innerHTML = 'I'm P!! ';
newP.style.backgroundColor = 'red';
Copy the code

insertBefore

Inserts an element object before an element tag in the specified container

[container].insertBefore([newEle],[oldEle])

Properties on the Node class prototype whose values are functions

<div id="box "class="box">2</div> // create var oDiv = document.createElement('div'); oDiv.id='div1'; oDiv.className='box'; oDiv.innerText='1'; document.body.insertBefore(oDiv,document.getElementById('box2')); / / you can write, also directly with the id of the document. The body. The insertBefore (oDiv box2);Copy the code

cloneNode

Clone a node [curELe]. CloneNode () : shallow clone, clone only the current label [curELe]. CloneNode (true) : deep clone, clone the current label and its contents together

Properties on the Node class prototype whose values are functions

<div class="box" id="box1">1</div> <div class="box" id="box2">2</div> <script> var box1=document.getElementById('box1'),  box2=document.getElementById('box2'); var box3=box2.cloneNode(); document.body.appendChild(box3); var box4=box2.cloneNode(true); document.body.appendChild(box4); </script>Copy the code

removeChild

RemoveChild ([curEle]) Node: Removes an element from the specified container. RemoveChild ([curEle]) Node prototype. The attribute value is a function

set/get/removeAttribute

SetAttribute ([key],[value]) Element prototype attributes. Attribute values are functions

What is the difference between using xxx.index=0 and xxx.setAttribute(‘index’,0) to set a custom attribute?

Xxx. index: Treat the current element as a normal object and give it an attribute name (independent of the HTML tag in the page).

Xxx. setAttribute: Treats elements as special element objects, setting custom attributes that are mapped to DOM elements in the page structure

Custom properties set using DOM methods and custom properties set by objects cannot be obtained from each other; the two methods are independent

  • The first method is to modify the heap memory space of the current element object based on the key-value pair operation of the object
  • The second is to modify the structure of the HTML tag on the page directly (custom attributes set in this way can be rendered in the structure).