I interviewed a guy who claimed to be a senior front-end, proficient in JS, proficient in VUE, and worked for 6 years. We don't play with the hypothetical either, let him feelInterview to build rockets, work to screw up
, then something real.
Q1:Do you know of any ways that JS can implement array traversal?
A1:for, for in, for of, foreach, map, etc., can all be used to traverse anyway".
Q2:So which of these methods can be interrupted?
A2:As if for can't, as if for in can ,..
Incoherent, lost in thought.
Come on, ladies and gentlemen, if you don't know, then you can read this articleFavorites + Likes
Encourage a wave.
forfor/infor/ofarray.foreacharray.maparray.reducearray.filterarray.somearray.Every method will not be nagged one by one, here is the key point.
Important: for in iterates over an object's enumerable properties other than symbol in any order. Therefore, for in is generally used to traverse an object. for of in iterable objects (inclusivearray
map
set
string
typedarray
, arguments, objects, etc.), invoke custom iteration hooks, and execute statements for the values of each different property. Therefore, for of is generally used to iterate over arrays. Note:
for in is unordered, you need to pay attention to the use of traversal, refer to: js puzzle-object in the key is ordered?What isEnumerable
?Take a closer look: Enumerable Highlight Examples:
Both to traverse the object let obj = ;// for/infor (var o in obj) ;// output// id// name// for/offor (var o of obj) ;The Error object is not an iterator and cannot be used for of VM319:1 Uncaught TypeError: Obj is not iterableAs you can see, for of cannot traverse an object.
Both iterate over the array let ary = ['a', 'b', 'c'];Note: Arrays are also a special object, and I add a property aryname = 'james'; // for/infor (var o in ary) ;output prints the array index and the value of the name property (note)!// 0// 1// 2// james// for/offor (var o of ary) ;output prints only the array for each element, a, b, cSo,
for/of
The advent of ES6 is also compensated to a certain extentfor/in
Defect in traversing arrays.
Important: create a new array (don't forget to putmap
The result is assigned to the traversal, otherwise a traversal is wasted) The original array is not affected (unless you put themap
Whenforeach
use, modify the value of the original array directly in the loop) each result of the new array is the value returned in the ** function (if your ** function forgets).reture
Each element of the new array isundefined
Typical Error Cases:
putmap
Used to iterate through arrays,map
, to directly modify the value of the original array
Example of error:
let demoary = [,demoary.map(item => )console.log(demoary);Correct example:
let demoary = [, method 1: foreach iterate through the array demoaryforeach(item => )console.log(demoary);Method 2: map generates a new array to replace the original array demoary = demoarymap(item => )console.log(demoary);Key points:
Produces a new result, and the result depends on the ** functionreturn
The value of the original array is not affected (unless you put itreduce
Whenforeach
use, modify the value of the original array directly in the loop) to receive 2 arguments,callbackwithinitialvaluecallbackThere are 4 parameters:Cumulative value
Current value
Current index
Raw value
, generally using the first 2 parametersinitialvalueOptionally, if you omit the default 1st element, but if the array is also empty, you will get an error with the important example:
There are initial values [1, 2, 3, 4, 5].reduce((acc, cur) => ,100);output iterates 5 times and finally returns the int sum of 115 100 1 101 2 103 3 106 4 110 5 115Without an initial value, the traversal will be one less because the first result of the array acts as the first value of the iterator.
There are no initial values [1, 2, 3, 4, 5].reduce((acc, cur) => ) output iterates 4 times, and finally returns the int sum result of 15 1 2 3 3 6 4 10 5 15Both are used to determine whether there are elements in the array that meet the conditions, and return the result
true
orfalse
Important: When using both, you must be clear about when to use themreturn true or false
to determine the result
Highlights Example:
// some[1, 2, 3, 4, 5].some(item => ;The default is false and can be omitted. It means that it cannot be found, and it will continue to traverse and find the last return false; of the array}) output iterate 3 times, find the result and return true 1 2 3 true
// every[1, 2, 3, 4, 5].every(item => ;The default is false, which must be written. If you don't explicitly state that this time is true, it means that the first element is not suitable, and it will be exited directly. return true;}) output iterate 3 times, find an inappropriate result and return false 1 2 3 falseLet's first look at how to break an array traversal:
BreakThrowReturnContinue (immediately end this loop, continue after ** does not execute, enter the next round of loop, it is considered to abort the current loop, and it is barely counted) forfor ofarraysomearray.Every of these methods we want:Interruptions
A common method for an array isarray.some
witharray.every
, because you have to meet certain conditions before you break an array traversal, right?It might be more appropriate to use these 2 syntactic sugars.
// for breaklet ary = [1, 2, 3, 4, 5];for (let i=0; i< ary.length; i++)// output// 0// 1// 2// 3// --// for continuefor (let i=0; i< ary.length; i++)console.log('after=', i);} output Note that there is no after=3 before= 0 after= 0 before= 1 after= 1 before= 2 after= 2 before= 3 before= 4 after= 4
// for/of breaklet ary = [1, 2, 3, 4, 5];for (let o of ary) ;// output// 1// 2// 3// --// for/of continuefor (let o of ary) ;console.log('after=', o);} output Note that there is no after=3 before= 1 after= 1 before= 2 after= 2 after= 2 before= 3 before= 4 after= 4 before= 5 after= 5Refer to the above for usage and will not repeat it.
These 2 methods are related to:for
withfor/of
The difference to note is that they break the syntaxreturn
It cannot be usedbreak
orcontinue