In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
The main content of this article is to explain "what is the method of traversing arrays and objects in JavaScript". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what is the method of traversing arrays and objects in JavaScript.
Array traversal
With the continuous development of JS, there are more than ten traversal methods up to ES7 specification. Let's introduce the common traversal methods of arrays according to a set of functionally similar methods.
For 、 forEach 、 for... of
Const list = [1, 2, 3, 4, 5, 6, 7, 8 for (let I = 0, len = list.length; I)
< len; i++) { if (list[i] === 5) { break; // 1 2 3 4 // continue; // 1 2 3 4 6 7 8 undefined 10 11 } console.log(list[i]);}for (const item of list) { if (item === 5) { break; // 1 2 3 4 // continue; // 1 2 3 4 6 7 8 undefined 10 11 } console.log(item);}list.forEach((item, index, arr) =>{if (item = 5) return; console.log (index); / / 0 1 2 3 5 6 7 9 10 console.log (item); / / 1 2 3 4 6 7 8 10 11})
Summary
All three are basic traversal arrays from left to right.
ForEach cannot jump out of the loop; for and for.. of can be skipped or interrupted using break or continue.
For... of directly accesses the actual element. For traverses the array index, and the parameters of the forEach callback function are more abundant, which can be obtained from elements, indexes, and original arrays.
For... of and for are also executed if there are empty elements in the array.
Some 、 every
Const list = [{name: 'header navigation', backward: false}, {name: 'carousel', backward: true}, {name: 'footer', backward: false},]; const someBackward = list.some (item = > item.backward); / / someBackward: trueconst everyNewest = list.every (item = >! item.backward); / / everyNewest: false
Summary
Both are used to determine array conditions, and both return a Boolean value.
Both can be interrupted.
Some returns true if an element meets the condition, and the loop is interrupted; if all elements do not meet the condition, false is returned.
Every, in contrast to some, returns false if the beneficial element does not meet the condition, and breaks the loop; if all elements meet the condition, true is returned.
Filter 、 map
Const list = [{name: 'header navigation', type: 'nav', id: 1}, {name:' carousel', type: 'content', id: 2}, {name:' footer', type: 'nav', id: 3},]; const resultList = list.filter (item = > {console.log (item); return item.type = =' nav';}) / / resultList: [/ / {name: 'header navigation', type: 'nav', id: 1}, / / {name:' footer', type: 'nav', id: 3}, / /] const newList = list.map (item = > {console.log (item); return item.id;})
Summary
Both generate a new array without changing the original array (excluding traversing the array of objects, manipulating element objects in the callback function)
Both skip empty elements. Students who are interested can print it by themselves.
Map forms a new array of the return values of the callback function, which is the same length as the original array.
Filter forms a new array of elements that meet the conditions of the callback function, and the length of the array is different from the original array.
The new array elements generated by map are customizable.
The new array elements generated by filter are not customizable and are consistent with the corresponding original array elements.
Find 、 findIndex
Const list = [{name: 'header navigation', id: 1}, {name: 'broadcast', id: 2}, {name: 'footer', id: 3},]; const result = list.find ((item) = > item.id = 3); / / result: {name: 'footer', id: 3} result.name = 'bottom navigation' / list: [/ / {name: 'head navigation', id: 1}, / / {name: 'carousel', id: 2}, / / {name: 'bottom navigation', id: 3}, / /] const index = list.findIndex ((item) = > item.id = 3); / / index: 2list.name / / 'bottom navigation'
Summary
Both are used to find array elements.
The find method returns the value of the first element in the array that satisfies the callback function. Returns undefined if it does not exist.
FindIndex returns the index of the element found in the array, not its value, or-1 if it does not exist.
Reduce 、 reduceRight
The reduce method takes two parameters, the first being the callback function (callback) and the second being the initial value (initialValue).
The reduceRight method is exactly the same except that the reduce executes in the opposite direction (from right to left).
The callback function takes four parameters:
Accumulator:MDN is interpreted as an accumulator, but I don't think it is appropriate. As far as I understand it, it should be the result of the accumulation of all previous array elements processed by callbacks as of the current element.
Current: the array element that is currently executed.
CurrentIndex: the currently executed index of array elements.
SourceArray: the original array, that is, the array that calls the reduce method.
If you do not pass in the initial value, the reduce method will execute the callback function from index 1, and if you pass the initial value, the callback will start at index 0 and accumulate from the initial value.
Calculate the sum of an attribute in an array of objects
Const list = [{name: 'left', width: 20}, {name:' center', width: 70}, {name: 'right', width: 10},]; const total = list.reduce ((currentTotal, item) = > {return currentTotal + item.width;}, 0); / / total: 100
Remove the weight of the object array and count the number of repetitions of each item
Const list = [{name: 'left', width: 20}, {name:' right', width: 10}, {name: 'center', width: 70}, {name:' right', width: 10}, {name: 'left', width: 20}, {name:' right', width: 10},]; const repeatTime = {}; const result = list.reduce ((array, item) = > {if (repeatTime [item.name]) {repeatTime [item.name] + Return array;} repeatTime [item.name] = 1; return [... array, item];}, []); / / repeatTime: {left: 2, right: 3, center: 1} / / result: [/ / {name: 'left', width: 20}, / / {name:' right', width: 10}, / {name: 'center', width: 70}, / /]
Get the maximum / minimum value of object array
Const list = [{name: 'left', width: 20}, {name:' right', width: 30}, {name: 'center', width: 70}, {name:' top', width: 40}, {name: 'bottom', width: 20},]; const max = list.reduce ((curItem, item) = > {return curItem.width > = item.width? CurItem: item;}); const min = list.reduce ((curItem, item) = > {return curItem.width {return true}) console.timeEnd ('every') / / some: 2.751708984375 msconsole.time (' some'); list.some () = > {return false}) console.timeEnd ('some') / / some: 2.786590576171875 msconsole.time (' foreach'); list.forEach () = > {}) console.timeEnd ('foreach'); / / foreach: 3.126708984375 msconsole.time (' map') List.map () = > {}) console.timeEnd ('map'); / / map: 3.743743896484375 msconsole.time (' forof'); for (let index of list) {} console.timeEnd ('forof') / / forof: 6.33380126953125 ms
As can be seen from the printing results, the speed of the for loop is the fastest and the for of loop is the slowest.
Termination of common traversal and comparison of performance tables
Whether it can be terminated or not
* * breakcontinuereturn performance (ms) for terminates ✅ jumping out of this cycle ✅❌ 2.42forEach ❌❌❌ 3.12map ❌❌❌ 3.74for of terminating ✅ jumping out of this cycle ✅❌ 6.33some ❌❌ return true ✅ 2.78every ❌❌ return false ✅ 2.75
Finally, there are some differences between different browser kernels, and students who are interested can also give it a try.
Object traversal
In object traversal, it is often necessary to traverse the keys and values of objects. ES5 provides for...in to traverse objects, but it involves enumerable properties of object properties, prototype chain properties, and so on. Here we will explore various methods of traversing objects from the nature of Object objects, and distinguish some of the characteristics of common methods.
For in
Object.prototype.fun = () = > {}; const obj = {2:'a', 1:'b'}; for (const i in obj) {console.log (I,':', obj [I]) } / / 1: bname / 2: a fun / fun: () = > {} the method extended on the Object prototype chain is also traversed out for (const i in obj) {if (Object.prototype.hasOwnProperty.call (obj, I)) {console.log (I,':', obj [I]);} / / name: an attributes that do not belong to themselves will be filtered by hasOwnProperty
Summary
When you use a for in loop, you return all enumerable properties that can be accessed through an object, including both those that exist in the instance and those that exist in the prototype. If you only need to get the instance properties of the object, you can use hasOwnProperty to filter.
When using (const x in a) instead of (x in a) the latter will create a global variable.
For the cycle order of for in, refer to [JavaScript authoritative Guide] (seventh edition) 6.6.1.
First list the string attributes whose names are non-negative integers, from lowest to largest in numerical order. This rule means that the properties of array and class array objects are enumerated in order.
After listing all the attributes of the class array index, list all the remaining string names, including those that look like integer negative or floating point numbers. These attributes are listed in the order in which they were added to the object. The attributes defined in the literal quantity of the object are listed in the order in which they appear in the literal quantity.
Finally, attributes named symbol objects are listed in the order in which they were added to the object.
Object.keys
Object.prototype.fun = () = > {}; const str = 'ab';console.log (Object.keys (str)); / / [' 0mm,'1'] const arr = ['averse,' b']; console.log (Object.keys (arr)); / / ['0mm,' 1'] const obj = {1: 'baked, 0:' a'}; console.log (Object.keys (obj)); / / ['0mm,' 1']
Summary
Used to get all the enumerable property values of the object itself, but not the properties in the prototype, and then return an array of property names.
Object.values
Object.prototype.fun = () = > {}; const str = 'ab';console.log (Object.values (str)); / / [' aqu,'b'] const arr = ['aqu,' b']; console.log (Object.values (arr)); / / ['ABA,' b'] const obj = {1: 'baked, 0:' a'}; console.log (Object.values (obj)); / / ['ABA,' b']
Summary
Used to get all the enumerable property values of the object itself, but not the properties in the prototype, and then return an array of property values.
Object.entries
Const str = 'ab';for (const [key, value] of Object.entries (str)) {console.log (`${key}: ${value}`);} / / 0: a value / 1: bconst arr = [' asides,'b']; for (const [key, value] of Object.entries (arr)) {console.log (`${key}: ${value}`) } / / 0: a key / 1: bconst obj = {1: 'banner, 0:' a'}; for (const [key, value] of Object.entries (obj)) {console.log (`${key}: ${value}`);} / / 0: a value / 1: B
Summary
Used to get all the enumerable property values of the object itself, but not the properties in the prototype, and then return a two-dimensional array. Each subarray consists of the property name and property value of the object. You can get both the attribute name and the attribute value.
Object.getOwnPropertyNames
Object.prototype.fun = () = > {}; Array.prototype.fun = () = > {}; const str = 'ab';console.log (Object.getOwnPropertyNames (str)); / / [' 0mm, '1mm,' length'] const arr = ['aqu,' b']; console.log (Object.getOwnPropertyNames (arr)); / / ['0mm,' 1mm, 'length'] const obj = {1:' baked, 0:'a'} Console.log (Object.getOwnPropertyNames (obj)); / / ['0mm,' 1']
Summary
Used to get all the enumerable property values of the object itself, but not the properties in the prototype, and then return an array of property names.
At this point, I believe you have a deeper understanding of "what is the method of traversing arrays and objects in JavaScript". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.