JS most detailed array method analysis

JS group detailed array method analysis


foreword

This article mainly summarizes the methods related to js arrays, including the usage of each method, and the scenarios of extended applications.

1. Array common methods

insert image description here

2. Use steps

Usage of each method (sorting in table order):

[].push()方法, add one or more elements at the end of the array and return the new length of the array. Note that what is changed is the value of the original array, and what is returned is the length of the new array.

let a = [1,2,3,4,5]
console.log(a.push(6))   // 返回数组长度6
console.log(a) // [1,2,3,4,5,6]

[].pop()方法, deletes the last element of the array and returns its deleted value. It also changes the original array and returns the deleted value.

let a = [1,2,3,4,5]
console.log(a.pop())     // 返回删除的元素5
console.log(a)  //[1,2,3,4]

[].unshift() 方法, similar to push(), the difference is that it is added at the head of the array, and everything else is the same

let a = [1,2,3,4,5]
console.log(a.unshift(2))    // 返回数组长度6
console.log(a)  //[2,1,2,3,4,5]

[].shift() 方法, similar to the pop() method, which deletes at the head of the array and returns its deleted value.

let a = [1,2,3,4,5]
console.log(a.shift())  // 返回删除的元素1
console.log(a)   // [2,3,4,5]

[].reverse()方法, returns the reversed string

let a = [1,2,3,4,5]
console.log(a.reverse())    // [5,4,3,2,1]
console.log(a)    // [5,4,3,2,1]

[].splice()方法, used to delete or insert elements, modify the original array.

var a = [1,2,3,4,5,6,7,8];
var b = a.splice(1,2); //第一个参数是截取的起始位置(包括),第二个参数是截取的个数,之后的参数就是添加在元数组的新值
console.log(a); //返回[1, 4, 5, 6, 7, 8]
console.log(b); //返回[2, 3]

[].sort方法, put back the sorted array

如果要数字从小到大排列:
var a = [2,3,1111,444];
a.sort(function (a,b) {
    
    
    return a-b
})           
console.log(a); //[2, 3, 444, 1111]
速记:
let result = arr.sort((a,b) => a - b);
let result = arr.sort((a,b) => b - a);

[].fill()方法, fill the array with fixed values

let a = [1,2,3,4]
a.fill(5)
console.log(a)  //返回[5,5,5,5]

[].join()方法, returns a string that is split and merged by the specified characters to form a string

let a = [1,2,3,4,5];
console.log(a.join()); // '1,2,3,4,5'
console.log(a.join('')); // '12345678'
console.log(a.join('=')); // '1=2=3=4=5'

[].concat()方法, creating and returning a new array

let a = [1,2,3,4,5]
console.log(a.concat([1,2]))  // 返回新的数组[1,2,3,4,5,1,2]
console.log(a)   // 原数组不变[1,2,3,4,5]

[].slice()方法, returns a segment or subarray of the specified array without changing the original array

let a = [1,2,3,4,5]
console.log(a.slice(1,3))   // [2,3]
console.log(a)    //  原数组不变[1,2,3,4,5]

[].map()方法, similar to forEach(), calls each element of the array to pass to the specified function, and returns an array, so the difference between it and forEach() is that it has a return value. The original array is not modified, and the returned array has the same length as the original array.

var a = [1,2,3,4,5];
var b = a.map(function (value) {
    
    
    return value+1
})
console.log(b); //返回[2,3,4,5,6]

[].reduce()方法, receiving a function as an accumulator, reduce executes the callback function for each element in the array in turn, excluding elements that are deleted or never assigned a value in the array.
reduce() more detailed analysis

//基本用法
const arr = [1, 2, 3, 4, 5]
const sum = arr.reduce((prev, cur) => {
    
    
    return prev + cur
}, 0)
console.log(sum) // 15
//当然也可以遍历数组
let a = [1, 2, 3, 4, 5, 6, 7, 8];
a.reduce((pre,cur) => {
    
    
    console.log(cur)
},0)

Array.from()method

//将伪数组变为数组可以用在dom元素中将获取的节点伪数组,变为真数组
//也可用于将可迭代对象变为数组
//例子1
<div class="d1"></div>
<div class="d1"></div>
<div class="d1"></div>
<script type="text/javascript">
    window.onload=function(){
    
    
        var d1 = document.getElementsByClassName('d1')
        console.log(d1)
        var d2 = Array.from(d1)
        console.log(d2)
    }
</script>
//例子2
let a = 'abcde'
let b = Array.from(a, v => v + v);
console.log(b); // ['aa','bb','cc','dd','ee']

Array.of(v1,v2,v3): Convert a series of values ​​into an array

let a = Array.of(1,'a',2,'b',3);
console.log(a);
// [1, "a", 2, "b", 3]

[].every(callback)According to the judgment condition, whether all the elements of the array are satisfied, if so, return true

let a = [1,2,3,4,5]
let b = a.every( (i) => i < 3)
console.log(b)    // 4,5不符合条件所以返回false

[].some()According to the judgment condition, whether one of the elements of the array satisfies, if one satisfies, true is the opposite of every

let a = [1,2,3,4,5]
let b = a.every( (i) => i < 3)
console.log(b)    //true

[].includes()It will judge whether the array contains a certain value. If it contains, it will return true, otherwise it will return false. There are two parameters. The first parameter indicates the value to be judged (required), and the second parameter indicates from which position in the array Start judging (optional).

let a = [1,2,3,4,5,6,7,8];
console.log(a.includes(2));
// true
console.log(a.includes(2,2));
// false ( 在 3,4,5,6,7,8 查找有没有 2 )

Array.isArray(), the most direct way to determine whether the passed value is an array

Array.isArray([1, 2, 3]);
// true
Array.isArray({
    
    foo: 123});
// false
Array.isArray("foobar");
// false
Array.isArray(undefined);
// false

[].forEach() 方法, traverse the array from beginning to end, calling the specified function for each element

var a = [1,2,3,4,5];
var sum = 0;
a.forEach(function (value) {
    
    
    sum += value
})
console.log(sum); //sum = 15
//例子
let arr = [1,2,3,4,5]
arr.forEach( (value,index,array)=>{
    
    
 console.log(`value:${
      
      value}    index:${
      
      index}     array:${
      
      array}`)
})   
//  value:1    index:0     array:1,2,3,4,5
//  value:2    index:1     array:1,2,3,4,5
//  value:3    index:2     array:1,2,3,4,5
//  value:4    index:3     array:1,2,3,4,5
//  value:5    index:4     array:1,2,3,4,5

let arr = [1,2,3,4,5]
arr.forEach( (value,index,array)=>{
    
    
   value = value * 2
   console.log(`value:${
      
      value}    index:${
      
      index}     array:${
      
      array}`)
})   
console.log(arr)
// value:2    index:0     array:1,2,3,4,5
// value:4    index:1     array:1,2,3,4,5
// value:6    index:2     array:1,2,3,4,5
// value:8    index:3     array:1,2,3,4,5
// value:10   index:4     array:1,2,3,4,5
// [1, 2, 3, 4, 5]

[].map()方法, similar to forEach(), calls each element of the array to pass to the specified function, and returns an array, so the difference between it and forEach() is that it has a return value. The original array is not modified, and the returned array has the same length as the original array.

var a = [1,2,3,4,5];
var b = a.map(function (value) {
    
    
    return value+1
})
console.log(b); //返回[2,3,4,5,6]

[].filter()方法, which returns a subset of the calling array.

var a = [1,2,3,4,5];
var b = a.filter(function (value) {
    
    
    return value > 3
})
console.log(b); //返回[4,5]

[].lengthGet the length of the array.

let a = [1,2,3,4,5,6,7,8];
console.log(a.length); // 8

indexOf()It will judge whether the array contains a certain value, return the index value of this value in the array if it is included, and return -1 if not, there are two parameters, the first parameter indicates the value to be judged (required), the second The parameter indicates from which position in the array to start judging (optional).

let a = [1,2,3,4,5,6,7,8];
console.log(a.indexOf(4)); // 3
console.log(a.indexOf(4,5));// -1 

lastIndexOf()It will judge whether the array contains a certain value, and the judgment method is "from right to left". If it is included, it will return the index value of this value in the array, if not, it will return -1. This method has two parameters, the first One parameter indicates the value to be judged (required), and the second parameter indicates where to judge from right to left in the array (optional, the default is the length of the entire array -1).

let a = [1,2,3,4,5,6,7,8];
console.log(a.lastIndexOf(3)); // 2
console.log(a.lastIndexOf(3,1));// -1 ( 只在1,2中判断,所以沒有 3 )

[].find()方法, will bring "every" element in the array into the specified function for judgment, and will return the first element that meets the judgment condition, if no element meets the judgment condition, it will return undefined.

let a = [1,2,3,4,5,6,7,8];
console.log(a.find(e => e > 3)); // 4
console.log(a.find(e => e < 0)); // undefined

[].toString()method to convert an array to a string (basically not used in this way)

Three, the method of traversing the array

In ES6, a for of loop was added

for(let v of [1,2,3,4]) {
    
      
    console.log(v);  
};  

注意:For in gets the key or array of the object, the subscript of the string, and for of is the same as forEach, it directly gets the value
for of不能遍历对like`

var set = new Set();  
set.add("a").add("b").add("c").add("d");  
var map = new Map();  
map.set("a",1).set("b",2).set("c",3);  
for (let v of set) {
    
      
    console.log(v);  
}  
console.log("--------------------");  
for(let [k,v] of map) {
    
      
    console.log(k,v);  
}

The for…of statement creates a loop to iterate over an iterable. The for…of loop introduced in ES6 to replace for…in and forEach(), and supports the new iteration protocol. for...of allows you to traverse Arrays (arrays), Strings (strings), Maps (maps), Sets (collections) and other iterable data structures.

4. Array deduplication method

Method 1: indexOf loop deduplication

//这里配合reduce方法实现去重,当然用for循环也是可以实现,主要方法还是indexOf
var arr = [1,2,3,4,4,5,5]
var newArr = arr.reduce(function (prev, cur) {
    
    
    prev.indexOf(cur) === -1 && prev.push(cur);
    return prev;
},[]);

Method 2: ES6 Set deduplication; Array.from(new Set(array))
one line of code deduplication:

let uniqArr = arr => [new Set(arr)];
console.log(uniqArr(arr));

Method 3: Object key-value pair deduplication; save the value of the array as the key value of Object, such as Object[value1]=true, when judging another value, if Object[value2] exists, it means that the value is Repeated


Summarize

So far, let’s summarize so much. If you encounter special uses related to arrays, you will add them. If there are mistakes, please point out and accept them humbly.

Guess you like

Origin blog.csdn.net/qq_43205326/article/details/114067377