当前位置:网站首页>JS array the usage of array is all here (array method reconstruction, array traversal, array de duplication, array judgment and conversion)

JS array the usage of array is all here (array method reconstruction, array traversal, array de duplication, array judgment and conversion)

2020-11-06 22:11:00 The front end of the attack

Ⅰ- one - Array basis

The difference between objects and arrays

 1.      An object is a loose structure , An object is a key value pair store , When you delete an element ,
         The other values of the object do not change , An object is the number of elements that have no elements , That's the object length 
         I don't know how many elements are stored in the object , Inserts and deletions don't affect other data , therefore 
         Very low time complexity , Because by key To store a value one by one , So when you get it , It only needs 
         according to key Just take the value , So the time complexity is very low . For objects , because 
         Every data is independent , There is no correlation , And it can't be sorted , So we don't look for connections to find 
         Corresponding value 



 2.      Arrays are compact structures , Only subscripts are used to store the corresponding values , When deleting an element is 
         Because of the close deconstruction , It's going to push the elements forward , An array has a length 
         You can know how many elements are stored in the array , Because inserting and deleting will affect the elements of the array 
         The position and Deconstruction of , Therefore, insertion and deletion will affect the efficiency of the array, and the time complexity is high 
         Arrays are stored by subscript , So if you need to find a value , You need to traverse the array 
         Every element , Reached, target element found , So the time complexity is very high . Arrays are using 
         when , Because it's compactness deconstruction , We can find other elements associated with it based on the previous content 
         For example, we can use arrays to sort , Find a minimum , You can also quickly find the second lowest value .

One Three ways to create arrays

  • If the constructor creates an array , There is only one parameter and this parameter is greater than or equal to 0
    The positive integer , This number is the length of the new array , And there are no elements . If it's negative
    Or decimals , You're going to report a mistake . If it's a non numeric type , This element will be placed in the first 0 position
var arr=[];
var arr=new Array();
var arr=new Object([]);

Two Array characteristics

  • An array is a list of references ,

  • Features of lists : The order , Only value , Close together , Slow speed .

  • Arrange disordered numbers in an orderly order

  • Arrays store only values , Can only traverse to get the value

  • When inserting arr[-1]=10 when , It doesn't increase the length .

  • It can be half an array and half an object

  • If it is added as needed, it will not be covered , Because the length changes

  • Array length cannot be negative

  • arr=[] Can't empty , This is a change of reference address

Array length usage brief introduction
arr.length=arr.length-1 If the length is one less than the original , The last element will be deleted
arr.length– To delete the last element
arr.length++ Means to add an empty element at the end
arr.length=0 Empty array
arr.length=true If you don't give a number , Will be implicitly converted to a number , If the value is NaN, You're going to report a mistake
arr[arr.length]=10 Add an element to the end of the array 10

3、 ... and Array attribute :

function ( Array name ) perhaps function ( Array name , value , value )

Array attribute explain
unshift() Add one or more elements to the beginning of an array , And returns the new length
push() Add one or more elements to the end of the array , And return the new length
pop() Delete and return the last element of the array
shift() Delete and return the first element of the array
join() Put all the elements of the array into a string . The element is divided by the specified separator
concat() Join two or more arrays , And return the result . Copy , Add new elements to the new array
splice () Remove elements , And add new elements to the array
slice() Returns the first selected element from an existing array
indexOf() Find the subscript of an element in an array , If there is no search, return to -1
lastIndexOf() Search back and forth
reverse() Reverse the order of the elements in the array
sort() Sort the array , Method to sort the elements of an array . Reference to array . It's going to change the array
es6 Method es6 Method
some() For each element of the array, judge whether the condition is satisfied , If you're not satisfied, go back to false, If there is one satisfied, return to true, And no longer judge what follows
every() For each element of the array, judge whether the condition is satisfied , If one of the conditions is not met, return false, When you are fully satisfied, return to true
reduce() Methods focus on each element of the accumulator and array ( From left to right ) Apply a function , Simplify it to a single value
filter() Method to create a new array , It contains all the elements of the test implemented by the provided function , Each element of the original array is passed into the callback function , There is... In the callback function return Return value , If the return value is true, This element is stored in a new array ; If the return value is false, Then the element is not saved in the new array ; The original array does not change .
fill() A method that replaces an array of elements

1. Delete and add attributes to the array

(1)unshift()
  1. unshift() Add several new elements to the front of the array
  2. unshift() Parameters are written directly , Array elements can be
  3. unshift() The return result is the length of the new array
  4. The original array will change

Refactoring properties

var arr = [3, 6, 2, 9];
	1function unshift(arr) {
   
		// Create a variable to store the maximum length of the parameter minus one ( Indexes 0 The storage is an array , From the index 1 Start looking for )
		// therefore let The value is 2
		var len=arguments.length-1;//2
		// Decreasing cycle ,i The initial value of arr The length of the minus one ,i The end value is 0;(arr The index is from 0 At the beginning ),
		//0 1 2 3 Index value 
		for (var i =arr.length-1; i >=0 ; i--) {
   
			//arr[i+len] Increase the length of the array .
			// First cycle  i=3 arr[i+len] The length is 5 
			// And arr[5]=arr[3] assignment ,arr The index for 3 The value of is assigned to arr Indexes 5
			arr[i+len]=arr[i];
		}
		// current arr by 
		// console.log(arr);//Array(6) [ 3, 6, 3, 6, 2, 9 ]
		// Pass the parameter value to the array 
		// From index to 1 The beginning of (23,5) Maximum length to parameter ;
		for (var j = 1; j < arguments.length; j++) {
   
			// First cycle : j=1;\
			//arr[0]=arguments[1];
			// The parameter index value is 1 The value of is assigned to arr Middle index 0;
			arr[j-1]=arguments[j];
		}
		// Back to the current length 
		return arr.length;
	}
	2function unshift(arr){
   
            var len=arguments.length-1;
            for(var i=arr.length-1;i>=0;i--){
   
                arr[i+len]=arr[i];
                arr[i]=null;
            }
           for(var j=1;j<arguments.length;j++){
   
               arr[j-1]=arguments[j];
           }
           return arr.length;
        } 
	unshift(arr,23,5);
	console.log(arr);//Array(6) [ 23, 5, 3, 6, 2, 9 ]
	console.log(unshift(arr));//6
(2)push()

Add one or more new elements to the end of the array , And return the new length of the array ;

  1. push() Append a new element to the end of the array
  2. push() Parameters are written directly , Array elements can be
  3. push() The return result is the length of the new array
  4. The original array will change

Refactoring properties

var arr=[3,6,2,9];
		function push(arr) {
   
			//arguments.length  Length of parameter   Here it means arr Length of array ;
			for (var i = 0; i < arguments.length; i++) {
   
				//  Each cycle , Will put arr Array index is i The value of is assigned to arr Maximum length of , Length plus one ; 
				arr[arr.length]=arguments[i];				
			}
			return arr.length;
		}		
		push(arr);
		console.log(push(arr));// 6
(3)shift(()

Deletes the first element of the array , And return this element

  1. shift() Delete the first element of the array

  2. shift() No parameters

  3. shift() The returned result is the deleted element

  4. The original array will change

    Refactoring properties

var arr = [3, 6, 2, 9];
	1function shift(arr) {
   
			// preservation arr The index for 0 Value 
			var len=arr[0];
			// Traversal array  arr Subtract one from the length to  arr The longest index of 
			for (var i = 0; i < arr.length-1; i++) {
   
				// First cycle :arr[0]=arr[1];
				// The second time :arr[1]=arr[2];
				// Assign the post value to the previous value 
				//
				arr[i]=arr[i+1];
				
				
			}
			console.log(arr);//Array(4) [ 6, 2, 9, 9 ]
			// Array length minus one , The last value is assigned to arr Maximum length index 
			arr.length=arr.length-1;
			
			return len;
		}
	2function shift(arr){
   
            var elem=arr[0];
            for(var i=1;i<arr.length;i++){
   
                arr[i-1]=arr[i];
            }
            if(arr.length>0) arr.length--;
            return elem;
        } 


		console.log(arr); //Array(3) [ 6, 2, 9 ]
		console.log(" The length of the array "+arr.length);//3
		console.log(" Returns the element "+shift(arr)); //3
(4)pop()
  1. Delete the last element of the array
  2. pop() Return deleted elements
  3. pop() No parameters
  4. The original array will change

Refactoring properties

var arr = [3, 6, 2, 9];
1function pop(arr) {
   
	// Use variables to store the value of the last index of the array 
	var len=arr[arr.length-1];
	// Array length minus one 
	arr.length--;
	
	return len;
}

2function pop(arr){
   
            var elem=arr[arr.length-1];
            if(arr.length>0) arr.length--;
            return elem;
        }


console.log(arr); //Array(4) [ 3, 6, 2, 9 ]
console.log(" The length of the array "+arr.length);//4
console.log(" Returns the element "+pop(arr)); //9

2 Array splicing and array segmentation

(1)join()
  1. Put all the elements of the array into a string . Elements are separated by a specified separator , Convert to string
  2. join() Returns the concatenated string
  3. join() The parameter is a character that is divided
  4. If the connector has no parameters , By default, it is linked with commas

Refactoring properties

var arr = [1, 2, 3];
1function join(arr, type) {
   
		// Define variable assignment as empty string .
		var str = "";
		// Traversal array ,
		for (var i = 0; i < arr.length; i++) {
   
			//+= All converted to strings ,
			str += arr[i] + type;
		}
		// Remove the last symbol  
		 if (type) str = str.substr(0, str.length - 1);

		return str;
	}	
2function join(arr,separator){
   
            if(separator===undefined) separator=",";
            separator=String(separator);
            var str="";
            for(var i=0;i<arr.length;i++){
   
               if(i!==arr.length-1) str+=arr[i]+separator;
               else str+=arr[i];
            }
            return str;
        }



	console.log(join(arr, "#"))//1#2#3
(2)concat()
1.  An array connects several arrays or elements 
  1. concat() Returns an array of new join completion , There is no reference relationship with the original array

Refactoring properties

var arr = [2, 9];
1function concat(arr) {
   
	var array = [];// Create an empty array , Store parameter array 
	var index=0;// It means array  The subscript of is from 0 At the beginning 
	
	// hold arr The values in the array are assigned to the new array array, index by array length   Equate to arr Array length of 
	for (var i = 0; i < arr.length; i++,index++) {
   
		array[index]=arr[i];
	}
	console.log(index);
	// If there is, except for arr Unexpected parameter to array ,arguments Get parameter length from zero , therefore for The initial value is 1  The subscript is 1,
	// After the end of the last cycle  index by 4
	for (var j = 1; j < arguments.length; j++,index++) {
   
		// Determine if it's an array 
		if(arguments[j].constructor===Array){
   
			//arguments[j].length: Indicates that the parameter is the maximum length of the array ,
			for (var k = 0; k < arguments[j].length; k++,index++) {
   
				//j=1;  The object whose parameter subscript is one ,k Indicates that the subscript is 1 The object index value of the parameter of ,
				//array[5]=arguments[1][0]
				//array[5]=arguments[1][1]
				//......
				// Assign to new array 
				array[index]=arguments[j][k];
			}
			
		}else{
   
			// If it's not an array , Direct assignment  , there j Indicates that it is not a subscript index of an array 
			// And then assign it to the new array , After performing   Add a length to the index value of the new array 
			
			array[index]=arguments[j];
			index++;
		}
	}
	// Return this new array 
	return array;
}

2function concat(arr){
   
            var arr1=[];
            for(var i=0;i<arr.length;i++){
   
                arr1[i]=arr[i];
            }
            if(arguments.length===1) return arr1;
            for(var j=1;j<arguments.length;j++){
   
                if(arguments[j]!==null && arguments[j].constructor===Array){
   
                    for(var k=0;k<arguments[j].length;k++){
   
                        arr1[arr1.length]=arguments[j][k];
                    }
                }else{
   
                    arr1[arr1.length]=arguments[j];
                }
            }
            return arr1;
        }



console.log(concat(arr,[3,4,5],67))

3 Array operation

(1)splice()
  1. How many elements are removed from the array starting from bit , And returns a new array of deleted elements
  2. How many elements are deleted from the first bit in the array , And insert a number of new elements in that position , Returns a new array of deleted elements
  3. Insert several elements at the beginning of the array , And it returns an empty new array
  4. arr.splice( Where to start , How many elements are deleted , Added elements …);
  5. It's going to change the array

Properties, :
Suppose there's an array var arr=[3,6,8,3,7,9];

usage Detailed explanation
var arr1=arr.splice(); Create an empty array ; Do not delete return an empty array
vsr arr1=arr.splice(0); Pass all elements of the array to the new array ( Delete 0 individual , The rest is returned to the new array )
vsr arr1=arr.splice(1); Delete to tail Returns an array of deleted elements
vsr arr1=arr.splice(-1); Delete... From back to front Returns an array of deleted elements
var arr1=arr.splice(-2); From the penultimate bit of the array to the tail Returns an array of deleted elements
var arr1=arr.splice(-2,3); Remove three elements from the penultimate position of the array Returns an array of deleted elements
var arr1=arr.splice(2,2); Delete from the second place 2 Elements Returns an array of deleted elements
var arr1=arr.splice(2,0,12,14); Insert elements 12,14 Insert at the beginning of the second place Change the original array No return value
var arr1=arr.splice(2,2,34,12); Replacement elements , Delete two digits and insert 12,14 Change the original array No return value
var arr1=arr.splice(1,0,0); Insert an element in the first place 0, Don't delete , Return an empty array Change the original array No return value

Refactoring properties

var arr=[3,6,8,3,7,9];
		function splice(arr,start,count) {
   
			// Create an array , To hold , For the returned array 
			var a=[];
			// The correctness of the parameters can be ensured by converting the parameters into numerical ones ;
			start=Number(start);//2  Where to start 
			count=Number(count);//1  Delete a few 
			// Judge whether the value of the parameter is numerical , If not   I'm just going to return this a Array 
			if(isNaN(start)) return a;
			// If there are parameters and greater than zero   The parameter is equal to the maximum length of the array  
			if(start<0) start+=arr.length;//8
			// Judge whether the value of the parameter is numerical ,count Is assigned as arr Array of 
			// Maximum length   Minus the degree start( Where to start )(count: How many elements are deleted )
			if(isNaN(count)) count=arr.length-start;//4
			
			//start=8,arr.length=6 count=1 
			for (var i = start,j=0; i < arr.length; i++,j++) {
   
				//push: Add one or more new elements to the end of the array , And returns the new length of the array 
				//
				if(j<count)a.push(arr[i]);
				arr[i]=arr[i+count];
			}
			//arguments.length-3=6  Parameter length after the third digit of the parameter , send arr Array length plus parameter length 
			for (var k = 0; k < arguments.length-3; k++) {
   
				for (var h = arr.length-1; h >=start+k; h--) {
   					
					arr[h+1]=arr[h];
				}
			}
			//
			for (var n = 3; n < arguments.length; n++) {
   
				// Starting from the third digit of the parameter , It's worth paying  arr Array   From  start(2) Start , Assign values in sequence   Increase in length 
				arr[start+n-3]=arguments[n];
				
			}
			console.log(arr);
			// Delete arr Length of array count(1)
			for (var s = 0; s < count; s++) {
   
				arr.length--;
			}
			return a;
		}
		var arr1=splice(arr,2,1,12,13,12,24,12,12);
		console.log(arr1,arr);
(2)slice()
  1. Returns the selected element from a known array
  2. It doesn't change the original array
  3. var arr1=arr.slice( Where to start , Before intercepting to where );
  4. Returns an array of intercepted elements It doesn't change the original array

Properties, :

usage Detailed explanation
var arr1=arr.slice(); There is no reference relationship between copying the original array and the new array , You can copy arrays var arr1=arr.splice(0) equally
var arr1=arr.slice(1); Copy from number one to the tail
var arr1=arr.slice(-2) 2; Copy from penultimate to tail
var arr1=arr.slice(2,3); Copy from the second to the third , We don't include the third, just copy the second
var arr1=arr.slice(-3,-1); Copy from the third to the last before the last
var arr1=arr.slece(2,-1); From the second to the last one

Refactoring properties

var arr = [3, 6, 8, 3, 7, 9];   
1function slice(arr, start, end) {
   
			// Convert to numeric 
			start = Number(start);
			end = Number(end);
			// It's not numerical  start=0
			if (isNaN(start)) start = 0;
			// It's not numerical  end by arr Length of array 
			if (isNaN(end)) end = arr.length;
			//
			//start, end With parameters 
			//start arr Array length plus arguments ;
			if (start < 0) start = start + arr.length;
			//arr Array length plus arguments ;
			if (end < 0) end = end + arr.length;
			var a = [];
			// if ,start,end None of them are filled in , Copy a arr Array , by a
			//start, end With parameters 
			//start, end With parameters   The index value is start(2) Start , The index value is end(4) Before ending excluding index is 4;
			for (var i = start, j = 0; i < end; i++, j++) {
   
				//i=2,j=0 i < 4
				//......
				//a[0] = arr[2];
				//arr Array 2-4 Assign a value between to a Array ;
				a[j] = arr[i];
			}
			return a
		}

2function slice(arr,start,end){
   
        if(start===undefined) start=0;
        if(end===undefined) end=arr.length;
        start=Number(start);
        end=Number(end);
        if(!isNaN(end) && isNaN(start)) start=0;
        if(isNaN(start)) return [];
        if(start<0) start=arr.length+start;
        if(end<0) end=arr.length+end;
        var arr1=[];
        for(var i=start;i<end;i++){
   
            arr1[i-start]=arr[i];
        }
        return arr1;
    }


		var arr1 = slice(arr, 2, 4);
		console.log(arr1, arr);

4 Array index method

(1)indexOf()
  1. Find the subscript of an element in an array , If there is no search, return to -1;
  2. indexOf() The parameter is the element of the search
  3. indexOf( The element to search for , Search from the subscript )

Refactoring functions

function indexOf(arr,search,index){
   
            if(index===undefined) index=0;
            for(var i=index;i<arr.length;i++){
   
                if(arr[i]===search) return i;
            }
            return -1;
        }
(2)lastIndexOf()
  1. arr.indexOf( Looking for elements , Start with the number one to find contained );
  2. Search back and forth

application :

var arr=[1,2,2,4,3,4,5,4,2,6,2,7];
	
	//
	var index=-1;
	// Look for the element 2, The index value is returned when it is found 
	while (~(index=arr.indexOf(2,index+1))){
   
		console.log(index);
	}
if (~indexof(2)) {
      // find 2 go in 
				
			}
(3)fill(()
  1. The padding method is used to replace the elements of an array with a fixed value .
  2. fill() Can only be used for arrays with length , If you don't give the start and end positions , It's going to be filled and covered
  3. fill() The parameter is the value to be filled in
  4. fill( The value to fill in , Where to start , Finish by what position );

application

// Create an empty array of length five 
var arr=new Array(5);
// Assign each property a value of 10
arr.fill(10);
console.log(arr);//Array(5) [ 10, 10, 10, 10, 10 ]

Ⅱ - Ii. - Array traversal

One Four traversal arrays

Traverse explain
for Traversal array
for in Loop can traverse the enumerable properties of an array to
forEachr Do not traverse empty arrays , It doesn't traverse properties either
Map The result is returned to the new array and can be incremented

1 for,for in

for in: Loop can traverse the enumerable properties of an array to , Cannot traverse empty elements of an array .

var arr=[1,2,3,,4,5,6];
for(var i=0;i<arr.length;i++){
   
    console.log(i,arr[i]);
}
// for in  Loop can traverse the enumerable properties of an array to 
// for in Cannot traverse to the empty element of an array 
for(var prop in arr){
   
    console.log(prop,arr[prop]);
}

in Determine whether the key value is There is

for(var i=0;i<arr. length;i++){
   
// console. log(arr[i]===undefined);
console.1og(i in arr);
}

You can judge this in the object key Whether the corresponding value exists ,
In an array, the subscript is equivalent to... In the object key, We can judge whether the corresponding value exists

for and for in

Using an array for Loop traversal , Will traverse all the subscripts , Do not traverse the array's object properties
But it will traverse to the empty element , Traversal is a subscript. It's all numeric

Using an array for in Loop traversal , All enumerable properties will be traversed , The attribute if
No value, no traversal , For example, an array with an empty subscript , It won't be traversed , however
The object properties of the array are traversed , When traversing, the subscript is converted into a string

2 forEach:

  1. Do not traverse empty arrays , It doesn't traverse properties either ,foreach It's an anonymous function , Can't block , Cycle break , Cycle out .
  2. forEach You can't return anything
  3. and for in Compare Does not traverse to array properties
  4. and for Compare , Does not traverse empty elements
  5. The disadvantage is that Will change this The direction of
var arr = [2, 4, 6, 8, 10, , 12, 14, 16, 18, 20];
//item:;index: Index value 
// usage :
arr.forEach(function (item,index,a) {
   
	console.log(item,index,a.length);
})

Refactoring properties , Bridging mode

1function forEace(arr,fn) {
   
	for (var i = 0; i < arr.length; i++) {
   
		// If there is no value, jump out of this loop and go to the next 
		if(arr[i]===undefined) continue;			
		// recursive 
		fn(arr[i],i,arr);
	}
}
2function forEach(arr,fn){
   
            for(var i=0;i<arr.length;i++){
   
                if(i in arr) fn(arr[i],i,arr);
            }
        } 


// Execute function .
// This is called   Bridging mode 
forEach(arr,function (item,index,a) {
   
	console.log(item,index,a);
})

3 Map

  1. Traversal array , And use return Returns the element , These returned elements will be placed in a new array
  2. The length of the new array is the same as that of the original array

usage :

var arr = [2, 4, 6, 8, 10 , 12, 14, 16, 18, 20];

var a=arr.map(function (item,index,a) {
   
	// console.log(item,index,a);
	return item+100;//a[102,104,106,108...]
})
console.log(a);

Refactoring properties

var arr = [2, 4, 6, 8, 10 , 12, 14, 16, 18, 20];
1function map(arr,fn) {
   
		// Create an empty array , Used to store the returned array 
		var a=[];
		// Traversal array 
		for (var i = 0; i < arr.length; i++) {
   
			// There is no value in the array , Then jump out of this cycle and enter the next cycle 
			if(arr[i]===undefined) continue;
			//
			a[i]=fn(arr[i],i,arr);
		}
		return a;
	}
2function map(arr,fn){
   
            var arr1=[];
            for(var i=0;i<arr.length;i++){
   
                if(i in arr) arr1[i]=fn(arr[i],i,arr);
            }
            return arr1;
        }



	// Execute function 
	var a=map(arr,function(item,index,a) {
   
			return item+100;
	});
	 console.log(a);

4 forEach and map The difference between

The difference lies in

  1. forEach no return value

  2. map There is a return value

Two Array property traversal method (es6)

The following properties all use bridge mode , Now let's briefly introduce the bridging mode

Gof The definition of , The function of bridging mode is to “ Isolate abstraction from its implementation , So that they can change independently “. This pattern is right for javascript Event driven programming, which is common in the .

(1)some()

For each element of the array, judge whether the condition is satisfied , If you're not satisfied, go back to false, If there is one satisfied, return to true, And no longer judge what follows

usage :

//some: Traversal array , Find out if there is a condition ( Return the result if it is true)
	// usage :
	 var arr=[1,2,3,4,5,6];
	var bool=arr.some(function(item,index,a){
   
	    return item>4;
	})
	console.log(bool);//true

Refactoring properties

var arr=[1,2,3,4,5,6];
1function some(arr,fn) {
   
	for (var i = 0; i < arr.length; i++) {
   
		if(arr[i]===undefined) continue;
		if(fn(arr[i],i,arr)) return true;
	}
	return false;
}
2function some(arr,fn){
   
            for(var i=0;i<arr.length;i++){
   
                if(i in arr && fn(arr[i],i,arr)) return true; 
            }
            return false;
        }

// perform 
var bool=some(arr,function (item) {
   
	return item>4;
});
console.log(bool);
(2)every()

For each element of the array, judge whether the condition is satisfied , If one of the conditions is not met, it is returned as false, Return when all is satisfied true
usage :

var arr = [1, 2, 3, 4, 5, 6];
var bool = arr.every(function(item) {
   
	return item > 4;
});
console.log(bool); //false

Refactoring properties

var arr = [1, 2, 3, 4, 5, 6];
1function every(arr, fn) {
   
	for (var i = 0; i < arr.length; i++) {
   
		if (!fn(arr[i], i, arr)) return false;
	}
	return true;
}
2function erery(arr,fn){
   
            for(var i=0;i<arr.length;i++){
   
                if(i in arr && !fn(arr[i],i,arr)) return false; 
            }
            return true;
        }



// perform 
var bool = every(arr, function(item) {
   
	return true;
})
console.log(bool);
(3)filter()
  1. Method to create a new array , It contains all the elements of the test implemented by the provided function , Each element of the original array is passed into the callback function , There is... In the callback function return Return value , If the return value is true, This element is stored in a new array ; If the return value is false, Then the element is not saved in the new array ;
  2. Screening Array
  3. It's an array Be careful It's got a subscript
  4. The original array does not change . It doesn't change the original array

application :
1

var arr=[1,2,3,4,5,6,7];
var arr1=arr.filter(function (item,index,a) {
   
	// Returns values greater than four in an array 
	return item>4;
})
console.log(arr1);

2

var data=[
    {
   id:1001,icon:"img/1.png",name:" Restaurant 0",num:1,price:10},
    {
   id:1002,icon:"img/2.png",name:" Restaurant 1",num:1,price:20},
    {
   id:1003,icon:"img/3.png",name:" Restaurant 2",num:1,price:30},
    {
   id:1004,icon:"img/4.png",name:" Restaurant 3",num:1,price:40},
    {
   id:1005,icon:"img/5.png",name:" Restaurant 4",num:1,price:50},
    {
   id:1006,icon:"img/6.png",name:" Restaurant 5",num:1,price:60},
    {
   id:1007,icon:"img/7.png",name:" Restaurant 6",num:1,price:70},
    {
   id:1008,icon:"img/8.png",name:" Restaurant 7",num:1,price:80},
    {
   id:1009,icon:"img/9.png",name:" Restaurant 8",num:1,price:90},
    {
   id:1010,icon:"img/10.png",name:" Restaurant 9",num:1,price:100}
];

// perform 1
var arr=data.filter(function(item){
   
    return item.price>60;
})
console.log(arr);
// perform 2
    var item=data.filter(function(item){
   
        return item.id==1006;
    })[0];
    console.log(item);

perform 1 The result is :
 Insert picture description here
perform 2 The result is :
 Insert picture description here
Refactoring properties

var arr=[1,2,3,4,5,6,7];
1function filter(arr,fn) {
   
	var a=[];
	for (var i = 0; i < arr.length; i++) {
   
	// It will be suspended after execution , Execute anonymous function to determine whether the condition is true, If it will be in a Add... To the end of the array arr Array current value 
		if(fn(arr[i],i,arr)) a[a.length]=arr[i];
	}
	return a;
}
2function filter(arr,fn) {
   
    if(arr.length===0) return arr1;
	var arr1=[];
	for (var i = 0; i < arr.length; i++) {
   
	
		if(fn(arr[i],i,arr)) arr1.push(arr[i])
	}
	return arr1;
}


// perform 
var arr1=filter(arr,function (item) {
   
	return item>3;
});
console.log(arr1);//Array(4) [ 4, 5, 6, 7 ]
(4)reduce()
  1. If the initial value is not set , The initial value of the last merge value is the first value of the array 0 term , This traversal will start from the subscript 1 Start . The second time of traversal value It will be the last time return The value returned

  2. If the initial value is set , The initial value of the last merge value is the initialization value , This traversal will start from the subscript 0 Start

  3. Form an object , It's not just about summation , Sure return All individual objects

  4. When each element of the array is completed, the last return value will be returned to the outside

application :

var arr = [1, 2, 3, 4, 5];
//( The value of the last merge , The elements of this traversal , Index value , Array )
var sum = arr.reduce(function(value, item, index, a) {
   
	// console.log(value,item);
	// return 10;
	console.log(value, item);
	return value + item;
}, 100);//100  For the initial value 
console.log(sum);


//  Maximum   minimum value 
   var arr=[1,2,3,40,5,6,7];
        var obj=arr.reduce(function(value,item){
   
            if(value.max==undefined) value.max=item;
            if(value.min==undefined) value.min=item;
            if(value.max<item) value.max=item;
            if(value.min>item) value.min=item;
            return value;
        },{
   });  // The initial value is {}  And  value yes {}
        console.log(obj);

Construct properties

var arr = [1, 2, 3, 4, 5];
function reduce(arr,fn,initValue) {
   
	var start=0;
	
	if(initValue===undefined){
   
		initValue=arr[0];
		start++;
	}
	for (var i = start; i < arr.length; i++) {
   
		initValue=fn(initValue,arr[i],i,arr)
	}
	return initValue;
}
// perform 
var sum=reduce(arr,function (value,item) {
   
	return value+item;
});
console.log(sum);

3、 ... and Case study

1 Generate captcha randomly out of order

var arr=[1,2,3,4,5,6,7,8];
        arr.sort(function(a,b){
   
            //  Random generation 0-1 Direct floating point numbers , barring 1
            return Math.random()-0.5
        });
        console.log(arr); */

      /* function getSecurityCode() { var arr = []; var i = 47; while (i++ < 122) { if (i > 57 && i < 65) continue; if (i > 90 && i < 97) continue; arr.push(String.fromCharCode(i)); } arr.sort(function(){ return Math.random()-0.5; }); arr.length=4; return arr.join(""); } console.log(getSecurityCode()); 

2 Select all button

HTML

<input type="checkbox" id="all" /><label for="all"> Future generations </label><br />
    <input type="checkbox" /><br />
    <input type="checkbox" /><br />
    <input type="checkbox" /><br />
    <input type="checkbox" /><br />
    <input type="checkbox" /><br />
    <input type="checkbox" /><br />
    <input type="checkbox" /><br />
    <input type="checkbox" /><br />
    <input type="checkbox" /><br />
    <input type="checkbox" /><br />

js

var all,list;
        init();
        function init(){
   
            list=document.getElementsByTagName("input");
            list=Array.from(list);
            all=list.splice(0,1)[0];
            all.onclick=clickHandler;
            list.forEach(function(item){
   
                item.onclick=clickHandler;
            })
        }

        function clickHandler(){
   
            // console.log(this);// In the click event this It's the clicked element 
            if(this===all){
   
                list.forEach(function(item){
   
                    item.checked=all.checked;
                })
            }else{
   
                all.checked=list.every(function(item){
   
                    return item.checked;
                })
            }
        }

Ⅲ - 3 - Array sorting

One Array sort properties

1 reverse In reverse order

  1. Just in reverse order , Don't order
  2. The original array changes , Return the original array

usage :

var arr=[1,4,6,2,3,8,7,6,5,3,9];
 arr.reverse();
 console.log(arr);//Array(11) [ 9, 3, 5, 6, 7, 8, 3, 2, 6, 4,  ]
var arr=["a","b","c","d"];
 arr.reverse();
 console.log(arr);//Array(4) [ "d", "c", "b", "a" ]

Refactoring properties

var arr=[1,4,6,2,3,8,7,6,5,3,9];
	1function reverse(arr){
   
     var len=parseInt(arr.length/2);
     for(var i=0;i<len;i++){
   
         // arr[arr.length-1-i]=arr[i];
         var temp=arr[arr.length-1-i];
         arr[arr.length-1-i]=arr[i];
         arr[i]=temp;
     }
     return arr;
 }
 2function reverse(arr){
   
           var arr1=[];
           for(var i=0;i<arr.length;i++){
   
               if(i in arr){
   
                  arr1[i]=arr[i];
               }
           }
           arr.length=0;
           for(var j=arr1.length-1;j>=0;j--){
   
                if(j in arr1){
   
                  arr[arr1.length-j-1]=arr1[j];
               }
           }
           return arr;
        }

 reverse(arr);

 console.log(arr);

2 sort Sort

  1. Method to sort the elements of an array . Reference to array .
  2. It's going to change the array

usage
sort Solution :

var arr=[1,4,6,2,3,8,7,6,5,3,9,10];
         arr.sort();//bug, You can't use it directly 
        arr.sort(function(a,b){
   
            //return a-b;// Ascending 
            return b-a;// Descending 
        })
         console.log(arr);
// Arrange randomly 0-100 Number 
var arr=[];
for(var i=0;i<100;i++){
   
    arr.push(i);
}
arr.sort(function(){
   
    return Math.random()-0.5;
});
console.log(arr);

Two Three array sorts

1 Bubble sort :

1、 Cycle back and forth
2、 Internal loop from front to back to outer variables
3、 Judge whether the former value is greater than the latter value , In exchange for

var arr=[1,4,6,2,3,8,7,6,5,3,9,10];
function sort(arr) {
   
	var len=arr.length;
	while(len>0){
   
		for (var i = 0; i < len; i++) {
   
			if(arr[i]>arr[i+1]){
   
				var temp=arr[i];
				arr[i]=arr[i+1];
				arr[i+1]=temp;
			}
		}
		len--;
	}
}
// perform 
sort(arr);
console.log(arr);

2 Selection sort

First find the minimum or maximum index value , Then exchange the current subscript element with the smallest element
1、 Traversal array
2、 Set the minimum index value to the current index value
3、 From the current next item to the end of the array
4、 Determine the smallest value index value of all traversal values
5、 Exchange the elements of the current value and the minimum index value

function sort(arr) {
   
	var mIndex;
	for (var i = 0; i < arr.length; i++) {
   
		mIndex=i;
		for (var j = i+1; j < arr.length; j++) {
   
			mIndex=arr[mIndex]<arr[j]?mIndex:j;
		}
		var trmp=arr[i];
		arr[i]=arr[mIndex];
		arr[mIndex]=trmp;
	}
}
// perform 
sort(arr);
console.log(arr);

3 Quick line up ( Quick sort )

        1、 Delete the elements in the middle of the array , also , Return this element to a variable 
        2、 Create two empty arrays , One is left, One is right, Traverse the array , take 
         Data smaller than the intermediate element is stored in left, Data larger than the intermediate element is stored in right
        3、 take left Array recursion and intermediate elements and right The results of array recursion are merged and returned 
        4、 At the top of the function , Be sure to write array length less than or equal to 1, Return the array 
var arr = [1, 4, 2, 2, 3, 10];
// Assign the result to arr Array ;
arr = sort(arr);
function sort(arr) {
   
	// If the length of this array is less than one, the array will be returned 
	if (arr.length <= 1) return arr;
	var left = [];
	var right = [];
	//
	var item = arr.splice(parseInt(arr.length / 2), 1)[0];
	for (var i = 0; i < arr.length; i++) {
   
		// If arr[i] Value 
		// Less than item Value   hold arr[i] This value is appended to left The end of the array 
		// Greater than item Value   hold arr[i] This value is appended to right The end of the array 
		if (arr[i] < item) {
   
			left.push(arr[i]);
		}else{
   
			right.push(arr[i]);
		}
	}
	// Pass two arrays through concat() Array attributes stitched together , Return a new array 
	var arrtow=sort(left).concat(item,sort(right));
	return arrtow;
}
// perform 
sort(arr);
console.log(arr);

Ⅳ - boss - Array weight removal

One Common de duplication

var arr=[1,2,2,4,3,4,5,4,2,6,2,7];
				 var arr1=[];
				 // loop arr Array 
				 for (var i = 0; i < arr.length; i++) {
   
				 	var bool=false;
					// The second time  arr[1] Value passed to arr  Array   The length is 1  Into the loop 
					for (var j = 0; j < arr1.length; j++) {
   
						//arr[1]===arr1[0] true
						//
						if(arr[i]===arr1[j]){
   
							// Change when there are values equal bool by true  Not adding values 
							bool=true;
							break;
						}
					}
					
					if(!bool){
   
						// First cycle 
						// by true When , Copy arr Array to arr1
						arr1.push(arr[i]);
					}	
				 }
				console.log(arr,arr1);

Two indexOf duplicate removal

var arr=[1,2,2,4,3,4,5,4,2,6,2,7];
	var arr1=[];
	for (var i = 0; i < arr.length; i++) {
   
	// Copy the number found to the new array 
		if(arr1.indexOf(arr[i])<0) arr1.push(arr[i]);
		}
	arr=arr1.splice(0);
	arr1=null;
	console.log(arr);

3、 ... and Array weight removal indexOf and delete

//delete Delete array elements , Does not cause the array to shrink automatically , Close together , The length of the array does not change 
var arr=[1,2,2,4,3,4,5,4,2,6,2,7];
	for (var i = 1; i < arr.length; i++) {
   
		
		//indexOf When found, the current value will be deleted , Search for ,
		// Start looking for 
		if(arr.indexOf(arr[i],i+1)>-1) delete arr[i];
		// Start looking for 
		if(arr.lastIndexOf(arr[i],i-1)>-1) delete arr[i];
	}
	var arr1=[];
	//
	for (let prop in arr) {
   
		arr1.push(arr[prop]);
	}
	arr=arr1.splice(0);
	arr1=null;
	console.log(arr);

Four filter,indexOf duplicate removal

arr=arr.filter(function(item,index,arr){
   
                    return arr.indexOf(item,index+1)<0;
            });
      arr.join(" ");

5、 ... and indexOf and delete duplicate removal

var arr=[1,3,3,6,8,2,3,5,6,3,7,9,8,3,6,7,3,8,9];
        for(var i=0;i<arr.length;i++){
   
            var index=i;
            while(index>-1){
   
                index=arr.indexOf(arr[i],index+1);
                if(index>-1)delete arr[i];// Use delete Becomes a loose array 
            }
        }
        // var arr1=arr.map(function(item){
   
        // return item;
        // });
        var arr1=[];
        arr.forEach(function(item){
   
            arr1.push(item);
        })


        console.log(arr1);

6、 ... and set duplicate removal

var arr=[1,3,5,7,2,4,3,5,1,2,6,5,7,8,9,1,2,4,3,5,7,9];
    arr=Array.from(new Set(arr));
    console.log(arr);

Ⅴ - wu - Array judgment and conversion

One Judge array

ES6:
console.log(Array.isArray(arr));
ES5:
console.log(Object.prototype.toString.call(arr)==="[object Array]");
console.log(arr.constructor===Array);

Two Convert to array

  1. Array.from(); Parameters are arguments to the transformation
Array.from();
Array.prototype.slile.call()
[].slice.call()

0 - 0 - Knowledge point :

Bridging mode

link https://blog.csdn.net/shanyongxu/article/details/47727471

arguments

ECMAScript Functions don't mind how many arguments are passed in , And it won't be wrong because the parameters are not uniform , actually , The body of a function can be passed through arguments Object to receive the parameters passed in .
arguments Object's length Attribute can get the number of parameters
We can use length This attribute , To judge intelligently how many parameters there are , Then the parameters are applied reasonably , such as , To implement an addition operation , Add up all the numbers passed in , And the number of numbers is uncertain .

An array with the JSON Conversion between strings

JSON.stringify() The role of the JavaScript Object to JSON character string , and JSON.parse() Can be JSON String to an object .
To put it simply , Their functions are relative , I use JSON.stringify() Put the object a It becomes a string c, Then I can use JSON.parse() The string c Restore to object a.

Array attribute induction

Array attribute explain
unshift() Add one or more elements to the beginning of an array , And returns the new length
push() Add one or more elements to the end of the array , And return the new length
pop() Delete and return the last element of the array
shift Delete and return the first element of the array
join() Put all the elements of the array into a string . The element is divided by the specified separator
concat() Join two or more arrays , And return the result . Copy , Add new elements to the new array
splice () Remove elements , And add new elements to the array
slice() Returns the first selected element from an existing array
indexOf() Find the subscript of an element in an array , If there is no search, return to -1
lastIndexOf() Search back and forth
reverse() Reverse the order of the elements in the array
sort() Sort the array , Method to sort the elements of an array . Reference to array . It's going to change the array
es6 es6
some() For each element of the array, judge whether the condition is satisfied , If you're not satisfied, go back to false, If there is one satisfied, return to true, And no longer judge what follows
every() For each element of the array, judge whether the condition is satisfied , If one of the conditions is not met, return false, When you are fully satisfied, return to true
reduce() Methods focus on each element of the accumulator and array ( From left to right ) Apply a function , Simplify it to a single value
filter() Method to create a new array , It contains all the elements of the test implemented by the provided function , Each element of the original array is passed into the callback function , There is... In the callback function return Return value , If the return value is true, This element is stored in a new array ; If the return value is false, Then the element is not saved in the new array ; The original array does not change .
fill() A method that replaces an array of elements

版权声明
本文为[The front end of the attack]所创,转载请带上原文链接,感谢