object
- One answer is to go back to the “classic” way of iterating object properties in JavaScript, before Object.entries() existed, like so:
const obj = { a: 1, b: 2, c: 3, } for (const key of Object.keys(obj)) { const value = obj[k] // Do something with 'value'... }
- for of
for (let group in data) { let groupFields = data[group] groupFields.forEach(field => { }) }
参考资料
- Object.entries()
The Object.entries() method returns an array of a given object’s own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for…in loop. (The only important difference is that a for…in loop enumerates properties in the prototype chain as well).
- TypeScript 3.x: Access properties of type unknown
- Object is of type ‘unknown’ - forEach and map
array
Iterating
- The following example shows how to use the for…of to iterate over elements of an array.
let scores = [80, 90, 70]; for (let score of scores) { score = score + 5; console.log(score); }
- To access the index of the array elements inside the loop, you can use the for…lop statement with the entries() method of the array.
The array.entries() method returns a pair of [index, element] in each iteration. For example:let colors = ['Red', 'Green', 'Blue']; for (const [index, color] of colors.entries()) { console.log(`${color} is at index ${index}`); }