Array de-weight? That is, remove duplicate elements from the array ...
First of all, the first method is to use the set set of properties to achieve the de-weight (in fact, a lot of set usage, interested can be more to understand the next);
What is a set set? Set set is a new data storage format;
Set syntax: New set ()
Parameters: An array
The set set can be called the fastest way to de-weight in history, as follows:
var arr = [1, 2, 3, 4, 5, 5, 4, 3, 2, 1 ]; var New set (arr); Console.log (set)
The second method is to encapsulate the good one function to determine if there is a value in the array, and then use this principle to do the array to weight; The code is as follows:
//determine if a value exists in the arrayfunctionhas (arr, n) {varBstop =false; for(varIincharr) { if(Arr[i] = =N) {bstop=true; Break; } } returnbstop;}functionNorepeat2 (arr) {varNEWARR = []; for(varIincharr) { if(!has (NEWARR, arr[i])) {Newarr.push (Srr[i])}} returnNEWARR;}
The third method is to use the new method of ES5 to indexof the weight;
IndexOf () function: Determines whether a character exists. Returns the corresponding subscript if it exists, or 1 if it does not exist;
How to achieve it, I believe that the little cutie have thought of the ~ code as follows:
function NOREPEAT3 (arr) { // Create a new array var newArr = []; // looping through arr for (var in arr) { // to determine the new array, if it does not exist for ARR, it is added to the new array if none exists If(Newarr.indexof (arr[i]) = =-1) { newarr.push (Arr[i]) } } return NEWARR}
The fourth method uses sort sort, creates a new array and then passes to the No. 0 of the original array, and when iterating, note that the initial value of I starts at 1. The code is as follows:
ARRAY.PROTOTYPE.NOREPEART4 =function(){ //Sort First This. sort (); //create a new array and deposit the No. 0 of the array varNEWARR = [ This[0]]; //iterate through the incoming array for(vari = 1;i< This. length;i++){ //take advantage of the value in each new array and the first I of the incoming array, which does not exist then push into the new array if(Newarr[newarr.length-1]! = This[i]) {Newarr.push ( This[i])}}//returns the new array returnNEWARR;}
Only unexpectedly not write out! There are a lot of ways to get the array out of the way, so here's a simple list of four. I hope everyone likes (hehe)
The method of the array de-weight of JS