当前位置:网站首页>Complete set of JS array common operations
Complete set of JS array common operations
2022-07-24 14:08:00 【Traces of running】
List of articles
- 1、push() Method
- 2、unshift() Method
- 3、pop() Method
- 4、shift() Method
- 5、filter() Method
- 6、join() Method
- 7、 indexOf() Method
- 8、reverse() Method
- 9、slice(start, end) Slicing method
- 10、splice(start, selectcount, ...items) Method
- 11、includes() Method ,
- 12、find() Method
- 13、concat() Method
- 14、sort(orderfunction) Method
- 15、map() Method
- 16、forEach() function
- 17、 some() function
- 18、 every() function
- 19、findIndex() function
- 20、fill() function
- 21、copyWithin() function
- 22、from() function
- 23、of() function
- 24、entries() function
- 25、values() iterator
- 26、keys() Return iterator
- 27、reduce() function
- 28、reduceRight()
1、push() Method
Add one or more elements to the end of the array , The return value is the value of the increased array length, The original array elements will also be changed
> var testArray = [1200,1100,2100,20];
> testArray.push(40,21);
6
> testArray;
[ 1200, 1100, 2100, 20, 40, 21 ]
2、unshift() Method
Add one or more elements to the array header , Return array length
> testArray.unshift(703,361)
8
> testArray
[ 703, 361, 1200, 1100, 2100, 20, 40, 21 ]
>
3、pop() Method
Will delete arrayObject Last element of , Reduce the length of the array by 1, And return the value of the element it deleted . If the array is already empty , be pop() Don't change the array , And back to undefined value .
> testArray.pop()
21
> testArray
[ 703, 361, 1200, 1100, 2100, 20, 40 ]
>
4、shift() Method
Used to remove the first element of the array from it , And returns the value of the first element , If the array is already empty , be shift() Don't change the array , And back to undefined value
> testArray.shift()
703
> testArray
[ 361, 1200, 1100, 2100, 20, 40 ]
>
5、filter() Method
Iterative method , Run the given function for each item of the array , In fact, that is arrayObject.filter( callback) , Give him a callback function ,
and callback The callback function passes in three parameters (item, index, originArray) Namely ‘item: Currently executing element ’ 、‘index: Current element subscript ’、‘originArray: Original array ’
If the return value is true, Keep the element ,false No reservation , When finished, return a new array
> testArray
[ 361, 1200, 1100, 2100, 20, 40 ]
> var filterRes = testArray.filter(function(e,i,arry){
return arry[i]<200})
> filterRes
[ 20, 40 ]
>
6、join() Method
join() Method is used to concatenate all elements in the array through the specified delimiter and return , By default , Division of no. , Do not change the original array .
> var resJoin = testArray.join('-')
> resJoin
'361-1200-1100-2100-20-40'
>
7、 indexOf() Method
The method of finding the index of the first occurrence of an element in the array lastIndexOf() Look backwards , Finally, the method of indexing elements All returned are index values , If no return is found -1 indexOf The second parameter is which index to start searching
> testArray
[ 361, 1200, 1100, 2100, 20, 40 ]
> testArray.indexOf(20)
4
> testArray.lastIndexOf(361)
0
> testArray.indexOf('test')
-1
> testArray.lastIndexOf('test')
-1
>
8、reverse() Method
Data reverse sort
> testArray.reverse()
[ 40, 20, 2100, 1100, 1200, 361 ]
>
9、slice(start, end) Slicing method
Return a return from start To end( Does not contain the element ) A new array of , This method does not modify the original array , Look at the following case from The first element is intercepted to the third , But it does not contain the third element
> testArray
[ 40, 20, 2100, 1100, 1200, 361 ]
> testArray.slice(1,testArray.length-3)
[ 20, 2100 ]
> testArray
[ 40, 20, 2100, 1100, 1200, 361 ]
>
Explain :
This can be seen start : from 0 Start end: It's from 1 Start Calculated
10、splice(start, selectcount, …items) Method
start From which index , selcetCount Delete a few , items Elements to be added after deletion
> testArray
[ 40, 20, 2100, 1100, 1200, 361 ]
> testArray.splice(3,1,999)
[ 1100 ]
> testArray
[ 40, 20, 2100, 999, 1200, 361 ]
>
11、includes() Method ,
The parameter is the value of the lookup , If there is a searched value in the array , The output “true”
> testArray
[ 40, 20, 2100, 999, 1200, 361 ]
> testArray.includes(2100)
true
>
12、find() Method
Return the first element that satisfies the filtering method , If none is satisfied, return undefined, After encountering a satisfied element, the traversal stops
> const testStrArray = [{
name:"Dex",age:20},{
name:"Lily",age:18},{
name:"Lielie",age:23}]
>
> const obtainRes = testStrArray .find((item)=>{
...
... return item.age == 18
...
... })
> obtainRes
{
name: 'Lily', age: 18 }
>
13、concat() Method
concat() Method to connect two or more arrays . This method does not change the original array , Only one copy of the connected array will be returned .
> const originArr = [{
name:'Jack',age:26}]
> const resConcat = testStrArray.concat(originArr)
> resConcat
[ {
name: 'Dex', age: 20 },
{
name: 'Lily', age: 18 },
{
name: 'Lielie', age: 23 },
{
name: 'Jack', age: 26 } ]
>
14、sort(orderfunction) Method
Sort the array by the specified parameters
> resConcat
[ {
name: 'Lily', age: 18 },
{
name: 'Dex', age: 10 },
{
name: 'Lielie', age: 23 },
{
name: 'Jack', age: 26 } ]
// Descending
> resConcat.sort((a,b) => b.age - a.age)
[ {
name: 'Jack', age: 26 },
{
name: 'Lielie', age: 23 },
{
name: 'Lily', age: 18 },
{
name: 'Dex', age: 10 } ]
// Ascending
> resConcat.sort((a,b) => a.age - b.age)
[ {
name: 'Dex', age: 10 },
{
name: 'Lily', age: 18 },
{
name: 'Lielie', age: 23 },
{
name: 'Jack', age: 26 } ]
>
15、map() Method
Run the given function for each item of the array , Returns the result of each function call to form a new array , The original array will not be changed
> testArray
[ 40, 20, 2100, 999, 1200, 361 ]
> var resMap = testArray.map(item => item * 2)
> resMap
[ 80, 40, 4200, 1998, 2400, 722 ]
> testArray
[ 40, 20, 2100, 999, 1200, 361 ]
>
16、forEach() function
Traversing every element of an array
> testArray.forEach(item => {
... console.log(item)
... })
40
20
2100
999
1200
361
>
17、 some() function
Run the given function for each item of the array , Any item returns ture, Then return to true
> var compare = function(item, index, originArr){
... return item > 100
... }
> testArray
[ 40, 20, 2100, 999, 1200, 361 ]
> testArray.some(compare)
true
>
> [80,99,98,20].some(compare)
false
>
18、 every() function
Run the given function for each item of the array , Each item returns ture, To return to true( This and some() Just the opposite )
> var compare = function(item, index, originArr){
... return item > 100
... }
> testArray
[ 40, 20, 2100, 999, 1200, 361 ]
> testArray.every(compare)
false
>
> [101,102,103].every(compare)
true
>
19、findIndex() function
Pass in a callback function , Find the first element in the array that matches the current search rule , Return its subscript , Terminate search .
> testFind
[ {
name: 'Dex', age: 10 },
{
name: 'Lily', age: 18 },
{
name: 'Lielie', age: 23 },
{
name: 'Jack', age: 26 } ]
> testFind.findIndex( item => item.age >20)
2
>
20、fill() function
arr.fill(value, start, end) Replace the elements in the array with new ones , You can specify a replacement subscript range .
> testFind
[ 123,
123,
{
name: 'Lielie', age: 23 },
{
name: 'Jack', age: 26 } ]
> testFind.fill(129,0,3)
[ 129, 129, 129, {
name: 'Jack', age: 26 } ]
>
Explain :
star: from 0 Start
end : Also from the 0 Start
21、copyWithin() function
arr.copyWithin(target, start, end)
Select a subscript of the array , Copy array elements from this location , The default from the 0 Start copying . You can also specify the range of elements to copy .
> const copyTest = [1,2,3,4,5,6]
> copyTest.copyWithin(3) // From the subscript 3 Start copying , Just before the array 1,2,3 The copy overwrites the following 4,5,6
[ 1, 2, 3, 1, 2, 3 ]
>
> const copyTest1 = [1,2,3,4,5,6]
> copyTest1.copyWithin(3,1) // Still subscript 3 Start copying , But specify the pasted value from the subscript 1 Start , So use 2,3,4 Covering the back 4,5,6
[ 1, 2, 3, 2, 3, 4 ]
>
> const copyTest2 = [1,2,3,4,5,6]
> copyTest2.copyWithin(3,2,3) // Still subscript 3 Start copying , But specify the pasted value from the subscript 2 Start , And the end position is 3 So just 3 To replace the 4 , hinder 5,6 Not pasted
[ 1, 2, 3, 3, 5, 6 ]
>
22、from() function
Will be like an array of objects (array-like object) Ergodic (iterable) The object of is converted to a real array
> Array.from('Hello')
[ 'H', 'e', 'l', 'l', 'o' ]
>
23、of() function
Used to put a set of values , Convert to array . Like new Array(1,2,3)
> Array.of('Hello','world',1,2,3)
[ 'Hello', 'world', 1, 2, 3 ]
>
> var ao = new Array(1,2,3)
undefined
> ao
[ 1, 2, 3 ]
>
24、entries() function
Each element corresponds to a subscript , Returns a new array similar to key value pairs
> var test = ['hi','no','yes']
> for(let i of test.entries()){
... console.log(i)
... }
[ 0, 'hi' ]
[ 1, 'no' ]
[ 2, 'yes' ]
> var testJson = [{
name:'dex',age:20},{
name:'jack',age:18}]
> for(let key of testJson.entries()){
... console.log(key)
... }
[ 0, {
name: 'dex', age: 20 } ]
[ 1, {
name: 'jack', age: 18 } ]
undefined
>
25、values() iterator
Return element value , Or iterate over the above object
> for(let key of testJson.values()){
... console.log(key)
... }
{
name: 'dex', age: 20 }
{
name: 'jack', age: 18 }
>
>
> var testMap = new Map([['name','Lili'],['tel',13609890132]])
> testMap
Map {
'name' => 'Lili', 'tel' => 13609890132 }
> for(let val of testMap.values()){
... console.log(val)
... }
Lili
13609890132
undefined
>
26、keys() Return iterator
similar json Get corresponding Of key
> testJson
[ {
name: 'dex', age: 20 }, {
name: 'jack', age: 18 } ]
> for(let key of testJson.keys()){
... console.log(key)
... }
0
1
>
>
> var testMap = new Map([['name','Lili'],['tel',13609890132]])
> testMap
Map {
'name' => 'Lili', 'tel' => 13609890132 }
> for(let key of testMap.keys()){
... console.log(key)
... }
name
tel
>
27、reduce() function
reduce It doesn't change the original array , Iterate over all items of the array , Then build a final return value , Start with the first item in the array , One by one to the end
arr.reduce(function(prev,cur,index,arr){
...
}, init);
perhaps
arr.reduce(function(prev,cur,index,arr){
...
},);
arr Represents the original array ;prev Represents the return value when the callback was last called , Or the initial value init;cur Represents the array element currently being processed ;index Represents the index of the array element currently being processed , If provided init value , The index is 0, Otherwise the index is 1;init Represents the initial value .
There are only two commonly used parameters :prev and cur.
Let's take a case to deepen our understanding
> var arr = [1, 2, 3, 2, 5];
>
> var sum2 = arr.reduce(function(pre, cur, index, array) {
... console.log(pre, cur,index, array)
... return pre+cur
... },10)
10 1 0 [ 1, 2, 3, 2, 5 ]
11 2 1 [ 1, 2, 3, 2, 5 ]
13 3 2 [ 1, 2, 3, 2, 5 ]
16 2 3 [ 1, 2, 3, 2, 5 ]
18 5 4 [ 1, 2, 3, 2, 5 ]
> sum2
23
>
1、 Array sum , Find the product
var arr = [1, 2, 3, 4];
var sum = arr.reduce((x,y)=>x+y)
var mul = arr.reduce((x,y)=>x*y)
console.log( sum ); // Sum up ,10
console.log( mul ); // Find the product ,24
2、 Count the number of occurrences of each element in the array
let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
let nameNum = names.reduce((pre,cur)=>{
if(cur in pre){
pre[cur]++
}else{
pre[cur] = 1
}
return pre
},{
})
console.log(nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}
3、 Array weight removal
> arr3
[
1, 2, 3, 5,
2, 3, 6
]
> var arr5 = arr3.reduce((pre,cur)=>{
... if(!pre.includes(cur)){
..... console.log('pre',pre,'cur',cur)
..... return pre.concat(cur)
..... }else{
..... console.log('else pre',pre)
..... return pre
..... }
... },[])
pre [] cur 1
pre [ 1 ] cur 2
pre [ 1, 2 ] cur 3
pre [ 1, 2, 3 ] cur 5
else pre [ 1, 2, 3, 5 ]
else pre [ 1, 2, 3, 5 ]
pre [ 1, 2, 3, 5 ] cur 6
>
> arr5
[ 1, 2, 3, 5, 6 ] // Finally, the array after de duplication
>
4、 Convert a two-dimensional array to a one-dimensional array
let arr = [[0, 1], [2, 3], [4, 5]]
let newArr = arr.reduce((pre,cur)=>{
return pre.concat(cur)
},[])
console.log(newArr); // [0, 1, 2, 3, 4, 5]
5、 Convert multidimensional arrays to one dimension
let arr = [[0, 1], [2, 3], [4,[5,6,7]]]
const newArr = function(arr){
return arr.reduce((pre,cur)=>pre.concat(Array.isArray(cur)?newArr(cur):cur),[])
}
console.log(newArr(arr)); //[0, 1, 2, 3, 4, 5, 6, 7]
6、 The sum of attributes in an object
var result = [
{
subject: 'math',
score: 10
},
{
subject: 'chinese',
score: 20
},
{
subject: 'english',
score: 30
}
];
var sum = result.reduce(function(prev, cur) {
return cur.score + prev;
}, 0);
console.log(sum) //60
28、reduceRight()
It doesn't change the original array , Iterate over all items of the array , Start with the last entry in the array , Go forward to the first item
var arr = [1, 2, 3, 2, 5];
> var sum3 = arr.reduceRight(function(pre, cur, index, array) {
... console.log(pre, cur,index, array)
... return pre+cur
... },10)
10 5 4 [ 1, 2, 3, 2, 5 ]
15 2 3 [ 1, 2, 3, 2, 5 ]
17 3 2 [ 1, 2, 3, 2, 5 ]
20 2 1 [ 1, 2, 3, 2, 5 ]
22 1 0 [ 1, 2, 3, 2, 5 ]
> sum3
23 23
>
Well, these are the basic ones commonly used
边栏推荐
- 在EXCEL表格中如何进行快速换行
- Statistical table of competition time and host school information of 2022 national vocational college skills competition (the second batch)
- 学习scipy minimize
- Flink fault tolerance mechanism (V)
- [oauth2] II. Known changes in oauth2.1
- 2021-07-09
- 使用树莓派做Apache2 HA实验
- "XXX" cannot be opened because the identity of the developer cannot be confirmed. Or what file has been damaged solution
- R language uses the tablestack function of epidisplay package to make statistical summary tables (descriptive statistics based on the grouping of target variables, hypothesis testing, etc.), set the b
- Mmdrawercontroller first loading sidebar height problem
猜你喜欢

Network security -- Service Vulnerability scanning and utilization

Nessus security testing tool tutorial

Network security - use exchange SSRF vulnerabilities in combination with NTLM trunking for penetration testing

Solve the problem that the ARR containsobject method returns no every time

Network security - Cookie injection

Network security - war backdoor deployment

天然气潮流计算matlab程序

Sringboot plugin framework implements pluggable plug-in services
![[C language note sharing] - dynamic memory management malloc, free, calloc, realloc, flexible array](/img/3f/35c9ff3be5c0ef781ffcb537287a20.png)
[C language note sharing] - dynamic memory management malloc, free, calloc, realloc, flexible array

Don't lose heart. The famous research on the explosive influence of Yolo and PageRank has been rejected by the CS summit
随机推荐
Nessus安全测试工具使用教程
Concurrent programming ----------- set
C# 多线程锁整理记录
Add an element to the object array with unshift
The fourth edition of probability and mathematical statistics of Zhejiang University proves that the absolute value of the correlation coefficient of random variables X and Y is less than 1, and some
The R language uses the DOTPLOT function of epidisplay package to visualize the frequency of data points in different intervals in the form of point graphs, uses the by parameter to specify the groupi
Multithreaded common classes
CSP2021 T1 廊桥分配
Detailed explanation of MSTP protocol for layer 3 switch configuration [Huawei ENSP experiment]
TypeError: 'str' object does not support item assignment
Flink高级特性和新特性(八)
No response to NPM instruction
Network security - file upload whitelist bypass
[C language note sharing] - dynamic memory management malloc, free, calloc, realloc, flexible array
Mini examination - examination system
达梦实时主备集群搭建
bibliometrix: 从千万篇论文中挖掘出最值得读的那一篇!
Network security - filtering bypass injection
字符串——28. 实现 strStr()
Flinktable & SQL (VI)