In JavaScript,entries()
and()
are two very practical built-in methods that can help us manipulate and access objects' properties in different ways. These two methods are very important to developers, especially when it is necessary to traverse and process the key-value pairs of objects. This article will explore these two methods in depth to help you fully understand their role and application scenarios, and further explain their usage methods through specific examples.
1. Detailed explanation of entries() method
1. Method introduction
()
is a method introduced by ES8 (ECMAScript 2017) that converts all enumerable properties of an object into an array containing key-value pairs. Each key-value pair is an array, where the first element is the attribute name and the second element is the corresponding attribute value.
For example:
const obj = { a: 1, b: 2, c: 3 }; ((obj)); // Output: [['a', 1], ['b', 2], ['c', 3]]
2. Usage and return value
()
Returns a two-dimensional array where each element is an array containing the keys and values of the object. This method will not traverse the non-enumerable attributes, nor will iterate over the properties on the prototype chain, but will only traverse the object's own enumerable attributes.
const person = { name: 'John', age: 30, job: 'developer' }; const entries = (person); (entries); // Output: [['name', 'John'], ['age', 30], ['job', 'developer']]
3. Application in array traversal
entries()
Methods are often used to passfor...of
Loop through the key-value pairs of the object. This method makes the code more concise and allows access to keys and values at the same time:
for (const [key, value] of (person)) { (`${key}: ${value}`); } // Output:// name: John // age: 30 // job: developer
This writing is very useful when dealing with complex objects, especially when dynamically processing object properties.
4. Application in arrays
In addition to being used in objects,()
It can also be used in arrays. For arrays, it returns the index of the array and the corresponding value as key-value pairs:
const arr = ['apple', 'banana', 'cherry']; ((arr)); // Output: [['0', 'apple'], ['1', 'banana'], ['2', 'cherry']]
In this way, you can easily get indexes and values while iterating through the array.
5. Application scenarios
-
Iterate over object properties: If you want to iterate over an object's properties and do some operations,
()
Provides an easy way. -
Process dynamic data: For dynamically generated objects, use
entries()
Each attribute and its value can be easily accessed. -
Convert object format: When it is necessary to convert the object's data into other forms (such as arrays, maps),
entries()
It is a very effective tool.
2. () Detailed explanation of the method
1. Method introduction
()
is another very useful method introduced by ES8, which returns an array containing the values of all enumerable properties of the object.
For example:
const obj = { a: 1, b: 2, c: 3 }; ((obj)); // Output: [1, 2, 3]
2. Usage and return value
()
Returns an array containing the object attribute values. and()
different,values()
Only care about the value of the object, not the key.
const person = { name: 'Alice', age: 25, job: 'designer' }; const values = (person); (values); // Output: ['Alice', 25, 'designer']
3. Array conversion
andentries()
Similar,()
It can also be applied to arrays. When used in an array, it returns all values in the array.
const arr = ['dog', 'cat', 'fish']; ((arr)); // Output: ['dog', 'cat', 'fish']
4. Purpose
-
Get the value of the object: If you only care about the value of the object and not the key,
()
It is a very simple method. -
Perform array operations: After converting an object into an array of values, you can use various methods of the array (such as
map()
,filter()
etc.) to handle it. - Simplify the code: By obtaining the value of the object, you can directly perform value-related operations without requiring additional access keys.
3. Use entries() and values() to achieve complex operations
Example: Find the shortest child array of an array
In actual development,entries()
and()
It can be used in combination to help us solve more complex tasks. For example, the following code needs to find the shortest subarray in the array so that the degree of the subarray (i.e. the frequency at which a number appears in the array) is maximum. For efficient processing, we usedentries()
and()
:
/** * @param {number[]} nums * @return {number} */ var findShortestSubArray = function(nums) { const mp = {}; // hash table, recording the frequency and position of each element // Iterate over the array and update the hash table for (const [i, num] of ()) { if (num in mp) { // If the number has already appeared, the update frequency and the last occurrence location mp[num][0]++; // Add one frequency mp[num][2] = i; // Update the last location } else { // If this number appears for the first time, the record frequency is 1, the first and last indexes are the current position mp[num] = [1, i, i]; } } let maxNum = 0, minLen = 0; // Maximum frequency and shortest sub-array length // traverse the hash table, find the elements with the largest degree, and calculate the corresponding subarray length for (const [count, left, right] of (mp)) { if (maxNum < count) { maxNum = count; // Maximum update frequency minLen = right - left + 1; // Update the shortest subarray length } else if (maxNum === count) { // If the frequency is the same, take the shortest sub-array length minLen = (minLen, right - left + 1); } } return minLen; // Return the shortest child array length};
Code explanation
entries()
Use of methods: In this code, we use()
Go through the arraynums
, get the index and corresponding value of each element. In this way, we can not only get the value, but also get the index of each element, which is very helpful for subsequent recording of the first and last positions of each element.
for (const [i, num] of ()) { // Iterate over the array and get the index i and element num}
()
Use of methods: Processing hash tablemp
When we use(mp)
Get all values, that is, the frequency of each element, the index that appears for the first time, and the index that appears for the last time. By traversing these values, we can judge the elements with the largest degree and calculate the shortest length of the corresponding subarray.
for (const [count, left, right] of (mp)) { // traverse the hash table value and calculate the maximum frequency and shortest sub-array length}
Applicable scenarios
-
Traversing complex data structures: Combined
entries()
and()
, can handle complex data structures concisely and efficiently, especially when you need to access keys and values simultaneously. - Optimize algorithm performance: Through these two methods, you can reduce extra code when iterating through objects and arrays, making the logic clearer.
This is the end of this article about the entries() and () methods in JavaScript. For more related JavaScript entries() and () content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!