当前位置:网站首页>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
边栏推荐
- XSS white list
- [C language note sharing] - dynamic memory management malloc, free, calloc, realloc, flexible array
- The latest and complete Flink series tutorials in 2021_ Preliminary exploration of Flink principle and flow batch integration API (II. V) V2
- 小熊派 课程导读
- Nessus安全测试工具使用教程
- uni-app 背景音频 熄屏或者退回桌面之后不在播放
- Summary of week 22-07-23
- SQL Server 启停作业脚本
- Network security -- Service Vulnerability scanning and utilization
- Uni app background audio will not be played after the screen is turned off or returned to the desktop
猜你喜欢

JS execution mechanism

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

Network security - file upload content check bypass

Matlab program for natural gas flow calculation

Solve the problem of repeated clicking of button uibutton

Nessus security testing tool tutorial

Nessus安全测试工具使用教程

Network security - Cookie injection

Unity pedestrians walk randomly without collision

Rhcsa sixth note
随机推荐
数据类型二进制字符串类型
Uni app background audio will not be played after the screen is turned off or returned to the desktop
Csp2021 T3 palindrome
Network security - filtering bypass injection
OWASP zap security testing tool tutorial (Advanced)
对话框管理器第二章:创建框架窗口
数据修改插入
Mmdrawercontroller first loading sidebar height problem
字符串——剑指 Offer 58 - II. 左旋转字符串
Detailed explanation of MSTP protocol for layer 3 switch configuration [Huawei ENSP experiment]
Data modification and insertion
String - Sword finger offer 58 - ii Rotate string left
Stack and queue - 20. Valid parentheses
Matlab program for natural gas flow calculation
Flink容错机制(五)
Introduction to the separation of front and rear platforms of predecessors
关于不定方程解的个数的问题
自动化渗透扫描工具
交换
看完这篇文章,才发现我的测试用例写的就是垃圾