entries of fetching iterative method for js array
- 2021-12-04 09:21:35
- OfStack
1. Detailed explanation of entires () method syntax
entries()
Method returns an iterative object of an array that contains the key-value pairs of the array
(key/value)
.
The index value of the array in the iteration object is used as the
key
The array element is used as the
value
. Its prototype
(__proto__:Array Iterator)
There is one on the
next
Method, which can be used to traverse the iterator to get the original array
[key,value]
. Here, you need to know the knowledge of related iterators.
2. Common use and attention of entires () method
2.1 Returning an Iterator Object
var arr = ["red", "blue", "green"]
var x = arr.entries()
console.log(x); // Array Iterator {}
console.log(x.next()) //{value: Array:[0, "red"],done:false}
console.log(x.next()) //{value: Array:[1, "blue"],done:false}
console.log(x.next()) //{value: Array:[2, "green"],done:false}
console.log(x.next()) //{value: undefined, done: true}
2.2 Use of for... of...
const options = [1, , , , 5];
for (const [index, value] of options.entries()) {
console.log(value);
}
// 0 1
// 1 undefined
// 2 undefined
// 3 undefined
// 4 5
2.3 2-Dimensional Array Row Sorting
function sortTwo(arr) {
var entries = arr.entries()
var flag = true
while (flag) {
var res = entries.next()
if (!res.done) {
res.value[1].sort((a, b) => a - b);
flag = true
} else {
flag = false
}
}
return arr
}
var arr = [[1, 3, 2], [44, 33], [11, 55, 44, 33]]
sortTwo(arr)
console.log(arr);// [[1, 2, 3], [33, 44], [11, 33, 44, 55]]
In the code above,
sortTwo
Method first gets the iteration object passed into the array, and then defines an initialization ID as
true
Invoking the iterative object recursively
entires
Adj.
(key/value)
0
Method to assign a value to
res
Object, judgment
res
Object's
d one
Property, if the value is
true
Indicates that it can be recursive,
res.value
Corresponding to every 1 row of the 2-dimensional array, you can sort the item. If the value is
flase
Indicates the end of recursion.
Summary: