当前位置:网站首页>Summary of traversal methods
Summary of traversal methods
2022-07-27 09:11:00 【Cabbage 007】
2.forEach((item,index,arry)=>{ })
for..in and for..of The difference between
7.some((item,index,array)=>{})
8.every((item,index,array)=>{})
8.reduce(callback,[initialValue]) Realize the accumulation of data
9.find() Specify element lookup
10.findIndex() Specify the element lookup subscript
1.for loop
Optimize : Use temporary variables , take length cached , Avoid duplicate acquisition length, stay length The effect is more obvious when it is larger .
var arr = [1, 2, 3, 4, 5, 6] var len = arr.length
for(var i = 0; i < len; i++) { console.log(arr[i]) } // 1 2 3 4 5 6
2.forEach((item,index,arry)=>{ })
More efficient for high , By default, there is no return value
When looping basic data types , It won't change the original data ;
When looping complex data types , Will change the object attribute value of the original data ;
var arr = [1, 2, 3, 4, 5, 6]
arr.forEach((item, idnex, array) => { console.log(item) // 1 2 3 4 5 6
console.log(array) // [1, 2, 3, 4, 5, 6] })
// The array elements of the loop are basic data types , Data that will not change the original data
var arr1 = [1, 2, 3, 4, 5, 6]
arr1.forEach((item) => { item = 10 }) console.log(arr1) // [1, 2, 3, 4, 5, 6]
// The array elements of the loop are objects , Will change the value of the object attribute of the original array
var arr2 = [ { a:1, b:2 } , { a:11, b:12 } ]
arr2.forEach((item) => { item.a = 10 })
console.log(arr2) // [{a: 10, b: 2}, {a: 10, b: 2}]
// Use try...catch... Can jump out of the loop
try {
let arr = [1, 2, 3, 4];
arr.forEach((item) => { // Jump out of the condition
if (item === 3) { throw new Error("LoopTerminates") ; } console.log(item) ; }); }
catch (e) { if (e.message !== "LoopTerminates") throw e ; } ; // 1 2
3.for key in array/object
You cannot traverse an empty array , Minimum efficiency
When traversing an array ,key Is the subscript of the array ;
When traversing objects ,key Is the property name of the object ;
var arr = [' I ', ' yes ', ' who ', ' I ', ' stay ', ' which ']
for(let key in arr) { console.log(key) } // 0 1 2 3 4 5
let obj = { a: 11, b: 22 , c: 33 }
for(let key in obj) { console.log(key) } // a b c
4.for key of array/string
Performance comparison for .. in .. good , a for Bad .
Be careful : Cannot traverse a loop object , As long as any data is deployed interator Interface , You can complete the traversal operation , Some data structures are native interator Interface , Such as array/map/set/string etc. , and interator Interface is deployed in Symbol.interator On the properties , The object object No, Symbol.interator attribute , So you can't traverse .
var arr = [' I ', ' yes ', ' who ', ' I ', ' stay ', ' which ']
for(var key of arr) { console.log(key) } // I yes who I stay which
for..in and for..of The difference between
for..in Only the key name of the object can be obtained , Can't get key value ; for..of Allow traversal to get key value ;
5.map() mapping
Performance comparison forEach Bad , It doesn't change the original array
Traverse each element and return the processed value , The length of the returned array is consistent with that of the original array
Be careful : Out of commission break/continue Jump out of array , Will report a mistake , have access to try..catch Jump out of array
var array = arr.map((item,index)=>{ return })
// One 、 It's going to change the array
var arr = [1, 2, 3, 4, 5, 6]
var newArr = arr.map(function (item, idnex) { return item * item })
console.log(arr) // [1, 2, 3, 4, 5, 6] console.log(newArr) // [1, 4, 9, 16, 25, 36]
// Two 、 Will change the attribute value of the object in the original array element
var arr = [{a: 1, b: 2},{a: 11, b: 12}]
let newARR = arr.map((item)=>{ item.b = 111 ; return item })
console.log('arr Array ',arr) // [{a: 1, b: 111},{a: 11, b: 111}]
console.log('newARR',newARR) // [{a: 1, b: 111},{a: 11, b: 111}]
// 3、 ... and 、 It doesn't change the original array
var arr = [{a: 1, b: 2},{a: 11, b: 12}]
let newARR = arr.map((item)=>{ return { ...item , b:111 } })
console.log('arr Array ',arr) // [{a: 1, b: 2},{a: 11, b: 12}]
console.log('newARR',newARR) // [{a: 1, b: 111},{a: 11, b: 111}]
// Four 、 Use try...catch... Can jump out of the loop
try { var arr = [1, 2, 3, 4];
arr.map((item) => { // Jump out of the condition
if (item === 3) { throw new Error("LoopTerminates") ; } console.log(item) ; return item });
} catch (e) { if (e.message !== "LoopTerminates") throw e ; } ; // 1 2
6.filter() Filter
Traversal array , Filter out the qualified elements and return a new array , When the conditions are not met , Return an empty array
var newarr = arr.filter((item,index)=>{ return Conditions })
var arr = [ { id: 1, name: ' Buy a pen ', done: true } , { id: 2, name: ' Buy a notebook ', done: true },
{ id: 3, name: ' practise calligraphy ', done: false } ]
var newArr = arr.filter(function (item, index) { return item.done }) console.log(newArr)
// [{ id: 1, name: ' Buy a pen ', done: true },{ id: 2, name: ' Buy a notebook ', done: true }]
7.some((item,index,array)=>{})
Traversal array , As long as there is an element that meets the condition, it returns true, Otherwise return to false;
It stops when one of the conditions is detected , Otherwise, continue the test .
var arr = [ { id: 1, name: ' Buy a pen ', done: true } , { id: 2, name: ' Buy a notebook ', done: true },
{ id: 3, name: ' practise calligraphy ', done: false } ]
var bool = arr.some(function (item, index) { return item.done })
console.log(bool) // true
8.every((item,index,array)=>{})
Traversal array , All elements meet the conditions and return true, Otherwise return to false
Be careful : Empty array call every return true
var arr = [ { id: 1, name: ' Buy a pen ', done: true } , { id: 2, name: ' Buy a notebook ', done: true },
{ id: 3, name: ' practise calligraphy ', done: false } ]
var bool = arr.every(function (item, index) { return item.done }) console.log(bool) // false
8.reduce(callback,[initialValue]) Realize the accumulation of data
arr.reduce(function(prev, cur, index, array){ // array: Original array prev: The return value of the last callback call , Or the initial value initcur: The array elements currently being processed index: The index of the array element currently being processed init: Initial value }, init)
array.reduce( ( accumulator,currentValue,currentIndex,array )=>{
accumulator: accumulator The result of each iteration
currentValue: Elements in the current array Will traverse the array Get the value in the array
currentIndex: The subscript of the current element in the array
array: Array object itself
initialValue: Optional parameters , It will affect accumulator The initial value of the , There are two situations :
If not initialValue, that accumulator From the first element in the array , here currentValue Will be taken from the second element in the array , Start the iteration
If given initialValue, that initialValue Will act as accumulator The initial value of the , here currentValue Will be taken from the first element in the array , Start the iteration
} [initialValue: Initial value ])
// Sum up varsum = arr.reduce(function (prev, cur) { return prev + cur; } , 0 ) ;
// Taking the maximum varmax = arr.reduce(function (prev, cur) { return Math.max(prev,cur ) ; });
9.find() Specify element lookup
Traversal array , The original array does not change and returns the first element that meets the condition , When there is no qualified element undefined
var arr = [1, 1, 2, 2, 3, 3, 4, 5, 6]
var num = arr.find(function (item, index) { return item === 3 }) console.log(num) // 3
10.findIndex() Specify the element lookup subscript
Traversal array , It doesn't change the original array , Returns the subscript of the first element that meets the condition , When there is no qualified element -1
var arr = [1, 1, 2, 2, 3, 3, 4, 5, 6]
var num = arr.findIndex(function (item) { return item === 3 }) console.log(num) // 4
边栏推荐
猜你喜欢

500 error reporting

async/await的执行顺序以及宏任务和微任务

The execution sequence of async/await, macro tasks and micro tasks

Deep understanding of Kalman filter (3): multidimensional Kalman filter

苹果降价600元,对本就溃败的国产旗舰手机几乎是毁灭性打击

【进程间通信IPC】- 信号量的学习

CUDA programming-02: first knowledge of CUDA Programming

BEVFormer: Learning Bird’s-Eye-View Representation from Multi-Camera Images via Spatiotemporal Trans

As a VC, the auction house invested Web3 for the first time
![Software testing function testing a full set of common interview questions [function testing - zero foundation] essential 4-1](/img/1c/c1c1b15e502ee901a396840c01e84d.png)
Software testing function testing a full set of common interview questions [function testing - zero foundation] essential 4-1
随机推荐
Intel, squeezed by Samsung and TSMC, finally put down its body to customize chip technology for Chinese chips
07_ Service registration and discovery summary
Common operations of BOM and compatible writing methods for obtaining page / window height, width and scrolling
Linux Installation and remote connection MySQL records
TensorFlow损失函数
Five kinds of 2D attention finishing (non local, criss cross, Se, CBAM, dual attention)
Size limit display of pictures
PyTorch自定义CUDA算子教程与运行时间分析
【Flutter -- GetX】准备篇
CUDA programming-04: CUDA memory model
Full Permutation recursive thought sorting
Qdoublevalidator does not take effect solution
MySQL基础知识学习(一)
拍卖行做VC,第一次出手就投了个Web3
Understand various IOU loss functions in target detection
函数防抖节流
Deep understanding of Kalman filter (3): multidimensional Kalman filter
flex:1的原理
BEVFormer: Learning Bird’s-Eye-View Representation from Multi-Camera Images via Spatiotemporal Trans
The lifecycle of arkui development framework components