How an array is defined
There are several ways to define an array, as follows
- Let array=[] (literal)
- let array=new Array()
- Let array=new array ([length]) Length indicates the length
- let array=new Array(arg1,arg2,arg3….)
let array=[]; // Initialize an empty array
let array2=new Array(a);// Initialize an empty array
let array3=new Array(10); // Initialize an array of length 10, each of which is empty
let array4=new Array(10.20.30.40);// initialize an array of length 4 with items 10,20,30,40
Copy the code
In development, let array=[] is the most commonly used and recommended.
Array add, delete, change, check
Adding an array
After you define an array, you need to add items to the array. Here are a few simple ways to do this.
- array[index]=xxx
- array[array.length]=xxx
let array=[];
array[0] =100;
array[1] =200;
console.log(array); / / 100, 200
let array2=[10.20];
array2[array.length]=30;
console.log(array2); / / 10 20 to 30
Copy the code
Array modification
If the item to be modified exists, perform the modification. If the item does not exist, perform the new operation
let array=[];
array[0] =100;
array[1] =200;
console.log(array); / / 100, 200
array[1] =300; // If the item exists, modify it
console.log(array); / / 100 300
Copy the code
Array deletion
Arr. Length = XXX XXX is less than the length of the array to delete items
let array=[];
array[0] =100;
array[1] =200;
console.log(array); / / 100, 200
array.length=0;
console.log(array); / / []
Copy the code
Array query
- Loop through each item, for loop, forEach loop, and so on
- Array [index], where index indicates an index
let array=[10.20.30.40.50];
console.log(array[0]); // Get the first item of the array, 10
for(let i=0; i<array.length; i++){console.log(array[i]); // run through each item of the group 10,20,30,40,50
}
Copy the code
Checks the array method and the array’s length property
After the Array is initialized, it has a length property that indicates the length of the Array, which I won’t cover here. Methods for checking arrays are instanceof and array.isarray ().
let array=[10.20.30.40.50];
console.log(Array.isArray(array)); // true
console.log(array instanceof Array); // true
Copy the code
We know that the array is an object, since it is an object, it must be inseparable from the attribute (Length) and method, about the attribute length, what, you understand, mainly introduce the array method, here is divided into ES5 array common method and ES6 array method.
Common methods for ES5 arrays
Conversion method
- Array.tostring () : Turns an Array into a comma-separated string
- Array.valueof () : Returns the Array itself
let array=[10.20.30.40.50];
console.log(array.toString()); / / 10,20,30,40,50
console.log(array.valueOf()); / /,20,30,40,50 [10]
Copy the code
Stack method (last in, first out)
- Array.push() : Adds one or more elements to the end of an Array and returns the new length of the Array
- Array.pop() : Removes the last element from the Array and returns the value of that element. This method changes the length of the array
let array=[];
array.push(10.20.30.40.50.60);
console.log(array);/ / 10,20,30,40,50,60
let item=array.pop();
console.log(item);/ / 60
console.log(array);// 10,20,30,40,50
Copy the code
Arr. Push ([1,2,3]) will not be 1,2,3. [1,2,3] will only be an item in the array. If you want to do this, you can use the ES6 extension operator…
let array=[10.20.30.40];
let array1=[50.60.70.80]; array.push(... array1);// Use the extension operator
console.log(array);/ / 10,20,30,40,50,60,70,80
Copy the code
Queue approach (first in, first out)
- Array.shift() : Removes the first element from the Array and returns the value of that element. This method changes the length of the array
- Array.unshift() : Method adds one or more elements to the beginning of an Array and returns the new length of the Array (this method modifies the original Array)
let array=[10.20.30.40];
let item=array.shift();
console.log(item); / / 10
console.log(array);/ / 20,30,40
array.unshift(100.200.300);
console.log(array);/ / 100200300,20,30,40
Copy the code
Reorder method
- Array.reverse() : Reverses the position of the elements in an Array and returns the Array. The first element of the array becomes the last, and the last element of the array becomes the first. This method changes the original array
- Array.sort() : Sorts the elements of an Array and returns the Array. The default sort order is built when converting elements to strings and then comparing their UTF-16 code unit value sequences
let array1=[10.20.30.40.50];
array1.reverse();
console.log(array1);/ / 50,40,30,20,10
let array2=[10.5.20.30.40.50];
array2.sort();
console.log(array2);/ / 10,20,30,40,5,50
Copy the code
As you can see from the console output, sort does not achieve the desired result, 5,10,20,30,40,50. This is because first sort calls the toString() transformation method for each item and then compares the resulting strings. To achieve the desired result, You can pass in a function to sort.
Array.sort(function(a,b){})
A: The first parameter used for comparison
B: The second parameter for comparison
Returns a negative number if the first argument should precede the second, 0 if two arguments are equal, and a positive number if the first argument should precede the second.
Array.sort() implements ascending order
let array=[10.20.40.50.30];
function compare(x,y) {
if(x<y){
return -1;
}else if(x>y){
return 1
}else {
return 0
}
}
array.sort(compare);
console.log(array); // 10,20,30,40,50
Copy the code
After sorting, we get the result of sorting in ascending order. If we want to do descending order, we can just switch the position
Arra.sort() implements descending order
let array=[10.20.40.50.30];
function compare(x,y) {
if(x<y){
return 1;
}else if(x>y){
return -1
}else {
return 0
}
}
array.sort(compare);
console.log(array); / / 50,40,30,20,10
Copy the code
For a numeric type or an object type whose valueOf() method returns a numeric type, you can simply subtract the second argument from the first argument
Operation method
-
Array.concat() : Used to merge two or more arrays. This method does not change an existing array, but returns a new array
-
Array.slice([start,end]) : This method can take one or two arguments, that is, the start and end positions of the item, with only one argument, and returns all items from the specified position to the end of the current Array. If there are two arguments, this method returns items between the start and end positions (but not the end positions).
-
Array. The splice () :
- Delete => You can delete any number of items by specifying two parameters, the location of the first item to be deleted and the number of items to be deleted
- Insert => You can insert any number of items into the specified position by providing 3 arguments, the starting position, 0, the item to insert, and if you want to insert more than one item, you can pass in the NTH item, the n+1 item,…
- Replace => You can insert any number of items into the specified position and delete any number of items at the same time by specifying 3 arguments, the starting position, the number of items to delete and any number of items to insert. The number of items to insert does not have to be the same as the number of items to delete
-
Array.join() : joins arrays using different symbols
Array.concat()
let array=[10.20.30.40];
let array1=[50.60];
let newArray=array.concat(array1);
console.log(newArray); / / 10,20,30,40,50,60
let array2=array.concat('20'[50.60].80);
console.log(array2); / / 10,20,30,40,20,50,60,80
Copy the code
Array.slice(start,end)
Start: indicates the index of the start position
End: indicates the index of the end position
let array=[10.20.30.40.50.60.70];
let array1=array.slice(1);// There is no end position, indicating from the start position to the end of the array
console.log(array1);/ / 20,30,40,50,60,70
let array2=array.slice(2.5); // Start index is 2, end index is 5(not including end index)
console.log(array2);/ / 30,40,50
Copy the code
Note: if the slice() method has a negative number in the start or end position, it is determined by the length of the array plus that number. For example: slice(-2,-1) is the same as slice(3,4) in a 5-item array, and returns an empty array if the end position is less than the start position.
Array.splice(index,item) deletes items
let array=[10.20.30.40.50];
array.splice(2.2); // Delete two entries from index 2
console.log(array); // 10,20,50
Copy the code
Array.splice(start,0,addItem) adds an operation
let array=[10.20.30];
array.splice(1.0.40.50.60);// add 40,50,60 from index 1
console.log(array); / / 10,40,50,60,20,30
Copy the code
Array.splice(start,deleteItem,addItem) implements the modification operation
let array=[10.20.30.40.50.60.70];
array.splice(2.2.90.100.110); // add 90,100,110
console.log(array);/ / 10,20,90,100,110,50,60,70
Copy the code
Note that you insert items before the current deleted item
Array.join()
This method can concatenate strings using different symbols. By default, no arguments are passed using commas (,)
let array=[10.20.30.40.50.60];
let array1=array.join(The '-');
let array2=array.join('|');
let array3=array.joing();
console.log(array1); / / the 10-20-30-40-50 to 60
console.log(array2); / / 10 20 30 | | | | | 50 to 60 40
console.log(array3); / / 10,20,30,40,50,60
Copy the code
Location method
- Array.indexof (searchElement,fromIndex) : Searches backwards from the beginning of the Array (position 0), returns -1 if none is found
- Array.lastindexof (searchElemengt,fromIndex) : Searches forward from the end of the Array, returns -1 if none is found
SearchElement: The element to find
FromIndex: Where to start the search
// 索引 0,1,2,3,4,5,6,7,8
let array=[1.2.3.4.5.4.3.2.1];
console.log(array.indexOf(4));// 3 finds the first occurrence of element 4
console.log(array.lastIndexOf(4));// 5 finds the last occurrence of element 4
console.log(array.indexOf(4.4)); // 5 finds the first occurrence of element 4 from index 4
console.log(array.lastIndexOf(4.4))// 3 Finds the last occurrence of element 4 from index 4
Copy the code
An iterative approach
- Array.every(function(item,index, Array)) : Runs the given function on each item in the Array, and returns true if the function returns true for each item
- Array.filter(function(item,index, Array)) : Returns an Array of items that return true by running the given function on each item in the Array
- Array.some(function(item,index, Array)) : Runs the given function on each item in the Array, and returns true if the function returns true for any item
- Array.foreach (function(item,index, Array)) : Runs the given function on each item in the Array. This method returns no value
- Array.map(function(item,index, Array)) : Runs the given function on each item in the Array and returns the Array returned as a result of each function call
let arrays=[1.2.3.4.5.4.3.2.1];
let everyResult=arrays.every((item,index,array) = >{
return item>10;
})
console.log(everyResult); // false
let someResult=arrays.some((item,index,array) = >{
return item>10
})
console.log(someResult); // false
let filterResult=arrays.filter((item,index,array) = >{
return item>2;
})
console.log(filterResult); / / 3,4,5,4,3
let mapResult=arrays.map((item,index,array) = >{
return item*2;
})
console.log(mapResult);/ / 2,4,6,8,10,8,6,4,2
arrays.forEach((item,index,array) = >{
console.log(item); / / 1,2,3,4,5,4,3,2,1
})
Copy the code
Note: None of the above methods modify the values contained in the array
Merge method
- Array.reduce() : Iterates through all the items in the Array, then builds a final returned value, starting with the first item in the Array and iterating through to the end
- Array.reduceright () : Iterate through all the items in the Array, and then build a final returned value, starting from the last item in the Array and moving forward to the first item
let array=[1.2.3.4.5];
let sum=array.reduce((prev,cur,index,array) = >{
return prev+cur
});
console.log(sum);
let sum2=array.reduceRight((prev,cur,index,array) = >{
return prev+cur
})
console.log(sum2);
Copy the code
Note: Reduce implements a number of functions that are briefly mentioned here
ES6 array new method
Array.from()
Used to convert class objects into true arrays, array-like objects, and traversable objects. Common class arrays are:
- Document. QuerySelectorAll () ‘tags’ for collection
- Function internal property Arguments object
Array.from() also supports array-like objects. Any object with length can be converted to an Array using array. from
let lis=document.querySelectorAll('li');
let arrays=Array.from(lis);
arrays.push(11111);
console.log(arrays);// li,li,li,11111
function foo() {
var args=Array.from(arguments);
args.push(10.20);
console.log(args); / / 10, 20
}
foo();
Copy the code
Array.of()
Used to convert a set of values into an array
Note: array.of () always returns an Array of parameter values, or an empty Array if there are no parameters
console.log(Array.of(3.11.8)); // 3,11,8
console.log(Array.of(3)); / / 3
console.log(new Array(1.2)); / / 1, 2
console.log(Array.of()); / / []
console.log(Array.of(undefined)); // undefined
console.log(Array.of(1)); // 1
console.log(Array.of(1.2)); / / 1, 2
Copy the code
Array.copyWithin(target,start=0,end=this.length)
Inside the current array, copies the member at the specified location to another location (overwriting the original member), and returns the current array
Parameters:
Target (required) : Replace data from this position, if negative, the reciprocal
Start (Optional) : reads data from this position. The default value is 0. If the value is negative, the value is calculated from the end
End (Optional): Stops reading data before this position. The default value is the length of the array. If it is negative, it is calculated from the end
[1.2.3.4.5].copyWithin(-2)
// [1, 2, 3, 1, 2]
[1.2.3.4.5].copyWithin(0.3)
// [4, 5, 3, 4, 5]
[1.2.3.4.5].copyWithin(0.3.4)
// [4, 2, 3, 4, 5]
[1.2.3.4.5].copyWithin(-2, -3, -1)
// [1, 2, 3, 3, 4]
Copy the code
Array.fill()
Fills an array with the given value
console.log(['a'.'b'.'c'].fill(7)); / / 7,7,7
console.log(new Array(3).fill(10)); / / 10,10,10
console.log(['a'.'b'.'c'].fill(7.1.2));// 'a',7,'c'
Copy the code
Array. The find () and Array. FindIndex ()
- Array.find() : Used to find the first eligible member of an Array. Its argument is a callback function that executes until it finds the first member that returns true, then returns that member, or undefined if there are no eligible members.
- Array.findindex () : Returns the location of the first qualified Array member, or -1 if all members fail
let item1=[1.4, -5.10, -6].find((n) = >n<=-5);
console.log(item1); / / - 5
let item2=[1.4, -5.10].find((item,index,arr) = >{
return item<-5
})
console.log(item2); // undefined
let item3=[1.5.10.15].findIndex((item,index,arr) = >{
return item>9
});
console.log(item3); // subscript 2
Copy the code
Array.includes()
Returns a Boolean value indicating whether an array contains a given value
[1.2.3].includes(2); // true
[1.2.3].includes(4); // false
[1.2.3].includes(3.3); // false
[1.2.3].includes(3, -1); // true
[1.2.NaN].includes(NaN); // true
Copy the code
Array. The flat () and Array. FlatMap ()
- Array.flat([depth]) : Used to flatline a nested Array into a one-dimensional Array. This method returns a new Array with no effect on the original data
- Array.flatmap () : Executes a function on each member of the original Array (equivalent to the array.map () method), and then executes the flat method on the Array of returned values, which returns a new Array without changing the original Array
Depth: Specifies the structure depth to extract the nested array. The default value is 1
let array1=[1.2[3.4]].flat();
console.log(array1); / / 1, 2, 3, 4
let array2=[1.2[3[4.5]]].flat();
console.log(array2) / / 1, 2, 3, [4, 5)
let array3=[1.2[3[4.5]]].flat(2);
console.log(array3);/ / 1, 2, 3, 4, 5
Copy the code
Array instance entries(), keys(), values()
Keys () : Traversal of array key names
Values () : Traversal of array key values
Entries () : Traversal of array key and value pairs
Arrays also have keys. Usually, the console.log() method is used to output its values. The keys represent the index
let array=[1.2.3.4.5];
for(let item of array.keys()){
console.log('the key is:'+item); / / 0,1,2,3,4
}
for(let item of array.values()){
console.log('value is:+item); / / 1, 2, 3, 4, 5
}
for(let [index,value] of array.entries()){
console.log(` button:${index}And the value:${value}`);
}
Copy the code
Array sorting method
Simple sorting of arrays
The sort method calls toString() for each item in an array. Let’s look at a simple example
<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8">
<title>Simple sorting</title>
</head>
<body>
<script type="text/javascript">
var numbers=[4.6.8.0.1.2.3.7.9];
numbers.sort();// Call the built-in array sort method
console.log(numbers);/ / 0,1,2,3,4,6,7,8,9
numbers.reverse();// Invert the array
console.log(numbers);/ / 9,8,7,6,4,3,2,1,0
</script>
</body>
</html>
Copy the code
<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8">
<title>Simple array custom sort</title>
</head>
<body>
<script type="text/javascript">
var number=[0.1.10.15.5];
function arrAsc(a,b){ // Implement the array ascending method
if(a>b){
return 1;
}else if(a<b){
return -1;
}else{
return 0;
}
}
number.sort(arrAsc);// Call the array ascending method
console.log(number);/ / 0.1, 5,10,15
function arrDesc(a,b){ // Implement the array descending method
if(a>b){
return -1;
}else if(a<b){
return 1;
}else{
return 0;
}
}
number.sort(arrDesc);// Call the array descending method
console.log(number);/ / 15,10,5,1,0
</script>
</body>
</html>
Copy the code
Object array sort
<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8">
<title>Simple object custom property sorting</title>
</head>
<body>
<script type="text/javascript">
var friuts=[
{
name:'apple'.price:18.5.count:10
},
{
name:'pear'.price:1.5.count:5}, {name:'banana'.price:20.5.count:20},]console.log(JSON.stringify(friuts));// before sorting
// Sort by ascending price
friuts.sort(function(x,y){
return x.price-y.price;
});
console.log(JSON.stringify(friuts));
// Sort by name
friuts.sort(function(x,y){
if(x.name>y.name){
return 1;
}else if(x.name<y.name){
return -1;
}else{
return 0; }});console.log(JSON.stringify(friuts));
</script>
</body>
</html>
Copy the code
Custom sorting methods
<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8">
<title>Generic sorting methods</title>
</head>
<body>
<script type="text/javascript">
var friuts=[
{
name:'apple'.price:18.5.count:10
},
{
name:'pear'.price:1.5.count:5}, {name:'banana'.price:20.5.count:20},]var sortExp=function(key,isAsc){
return function(x,y){
if(isNaN(key)){
if(x[key]>y[key]){
return 1*(isAsc?1: -1);
}else if(x[key]<y[key]){
return -1*(isAsc?1: -1);
}else{
return 0; }}else{
return (x[key]-y[key])*(isAsc?1: -1)}}}// The price is in ascending order
friuts.sort(sortExp('price'.true));
console.log(JSON.stringify(friuts));
// Prices are in descending order
friuts.sort(sortExp('price'.false));
console.log(JSON.stringify(friuts));
// Name in ascending order
friuts.sort(sortExp('name'.true));
console.log(JSON.stringify(friuts));
// Name in descending order
friuts.sort(sortExp('name'.false));
console.log(JSON.stringify(friuts));
// The quantity is in ascending order
friuts.sort(sortExp('count'.true));
console.log(JSON.stringify(friuts));
// The quantity is in descending order
friuts.sort(sortExp('count'.false));
console.log(JSON.stringify(friuts));
</script>
</body>
</html>
Copy the code
12 ways to remove weight from handwritten arrays
1. Use Set in ES6 to implement deduplication (most commonly used in ES6)
function unique (arr) {
return Array.from(new Set(arr))
}
let array=[1.2.3.1.2.'true'.'true'.false.false.undefined.undefined.null.null.NaN.NaN, {}, {}]console.log(unique(array));/ / 1, 2, 3, 'true, false, undefined, null, NaN, {}, {}
Copy the code
Disadvantages: You can see that {} cannot be de-duplicated
2. Use double for loops and splice for de-duplication (ES5)
function unique(array){
for(let i=0; i<array.length; i++){// The outer loop element
for(let j=i+1; j<array.length; j++){// Compare values in the inner layer
if(array[i]==array[j]){
array.splice(j,1); j--; }}}return array;
}
let array=[1.2.3.1.2.'true'.'true'.false.false.undefined.undefined.null.null.NaN.NaN, {}, {}];console.log(unique(array)); / / 1, 2, 3, 'true, false, undefined, NaN NaN, {}, {},
Copy the code
Double loop, outer loop elements, inner loop when comparing values. If the values are the same, delete this value
Cons: Null disappears directly, NaN and {} cannot be de-duplicated
3. Use indexOf to implement de-duplication
function unique(arr) {
let array = [];
for (let i = 0; i < arr.length; i++) {
if (array.indexOf(arr[i]) === -1) {
array.push(arr[i])
}
}
return array;
}
let array=[1.2.3.1.2.'true'.'true'.false.false.undefined.undefined.null.null.NaN.NaN, {}, {}];console.log(unique(array));/ / 1, 2, 3, 'true, false, undefined, null, NaN, NaN {}, {}
Copy the code
Disadvantages: NaN and {} cannot be de-duplicated
4. Use sort() to implement de-duplication
function unique(arr) {
arr = arr.sort()
let array= [arr[0]].for (let i = 1; i < arr.length; i++) {
if(arr[i] ! == arr[i-1]) { array.push(arr[i]); }}return array;
}
let array=[1.2.3.1.2.'true'.'true'.false.false.undefined.undefined.null.null.NaN.NaN, {}, {}];console.log(unique(array));// 1, 2, 3, NaN, NaN, {}, {}, false, null, "true", undefined
Copy the code
Use sort() sorting method, and then traverse and compare adjacent elements according to the sorted result.
Disadvantages: NaN and {} cannot be de-duplicated
5. Using the attributes of an object cannot achieve the same characteristics of de-duplication
function unique(arr) {
let array= [];
let obj = {};
for (var i = 0; i < arr.length; i++) {
if(! obj[arr[i]]) { array.push(arr[i]) obj[arr[i]] =1
} else {
obj[arr[i]]++
}
}
return array;
}
let array=[1.2.3.1.2.'true'.'true'.false.false.undefined.undefined.null.null.NaN.NaN, {}, {}];console.log(unique(array));// 1, 2, 3, "true", false, undefined, null, NaN, {}
Copy the code
6. Use includes to implement de-duplication
function unique(arr) {
let array =[];
for(let i = 0; i < arr.length; i++) {
if(! array.includes( arr[i]) ) { array.push(arr[i]); }}return array
}
let array=[1.2.3.1.2.'true'.'true'.false.false.undefined.undefined.null.null.NaN.NaN, {}, {}];console.log(unique(array));// 1, 2, 3, "true", false, undefined, null, NaN, {}, {}
Copy the code
Disadvantages: {} cannot implement de-duplication
7. Use hasOwnProperty to implement de-duplication
function unique(arr) {
let obj = {};
return arr.filter(function(item, index, arr){
return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)})}let array=[1.2.3.1.2.'true'.'true'.false.false.undefined.undefined.null.null.NaN.NaN, {}, {}];console.log(unique(array));// 1, 2, 3, "true", false, undefined, null, NaN, {}
Copy the code
Use hasOwnProperty to determine whether an object property exists
8. Use filter to implement deduplication
function unique(arr) {
return arr.filter(function(item, index, arr) {
return arr.indexOf(item, 0) === index; NaN cannot implement lookups
});
}
let array=[1.2.3.1.2.'true'.'true'.false.false.undefined.undefined.null.null.NaN.NaN, {}, {}];console.log(unique(array));/ / 1, 2, 3, 'true, false, undefined, null, {}, {}
Copy the code
Cons: NaN is missing and {} can’t be de-duplicated
9. Use recursion to achieve de-duplication
function unique(arr) {
var array= arr;
var len = array.length;
array.sort(function(a,b){ // It is more convenient to remove the weight after sorting
return a - b;
})
function loop(index){
if(index >= 1) {if(array[index] === array[index-1]){
array.splice(index,1);
}
loop(index - 1); // loop recursively, then the array is deduplicated
}
}
loop(len-1);
return array;
}
let array=[1.2.3.1.2.'true'.'true'.false.false.undefined.undefined.null.null.NaN.NaN, {}, {}];console.log(unique(array));/ / false, null, 1, 2, 3, 'true' NaN, NaN, {}, {}, undefined
Copy the code
Cons: {},NaN does not implement de-duplication
10. Use Map data structure to implement de-duplication
function arrayNonRepeatfy(arr) {
let map = new Map(a);let array = new Array(a);// The array is used to return the result
for (let i = 0; i < arr.length; i++) {
if(map .has(arr[i])) { // If there is a key value
map .set(arr[i], true);
} else {
map .set(arr[i], false); // If there is no key valuearray .push(arr[i]); }}return array ;
}
let array=[1.2.3.1.2.'true'.'true'.false.false.undefined.undefined.null.null.NaN.NaN, {}, {}];console.log(arrayNonRepeatfy(array));/ / 1, 2, 3, 'true, false, undefined, null, NaN, {}, {}
Copy the code
Create an empty Map data structure that iterates through the array to be repealed, storing each element of the array as a key in the Map. Since the Map does not have the same key value, the final result is the result after the deduplication.
Disadvantages: {} does not implement de-duplication
11. Use Reduce +includes to implement de-duplication
function unique(arr){
return arr.reduce((prev,cur) = > prev.includes(cur) ? prev : [...prev,cur],[]);
}
let array=[1.2.3.1.2.'true'.'true'.false.false.undefined.undefined.null.null.NaN.NaN, {}, {}];console.log(unique(array));/ / 1, 2, 3, 'true, false, undefined, null, NaN, {}, {}
Copy the code
Disadvantages: {} does not implement de-duplication
[…new Set(arr)
let array=[1.2.3.4.5.1.2.3.4];
let newArray=[...new Set(array)];
console.log(newArray); / / 1, 2, 3, 4, 5
Copy the code
At the end
Through the study of this blog, I believe you have a closer understanding of the array, if you think this blog is helpful to you, remember to give the author three lien, like 👍👍👍, pay attention to, collect, your support is the biggest power on my writing road, we will see the next article.
The resources
Developer.mozilla.org/zh-CN/docs/…
Segmentfault.com/a/119000001…
es6.ruanyifeng.com/#docs/array
JavaScript Advanced Programming (version 3)