LOOP

for-of and for-in

1
2
3
4
5
6
7
8
9
10
11
for (const item of restaurant.starterMenu) console.log(item);
//Focaccia
//Bruschetta
//Garlic Bread
//Caprese Salad
for (const index in restaurant.starterMenu) console.log(index);
//0
//1
//2
//3
//4
  • Item is always the current element in each iteration.

  • Index is always the current index or property name in each iteration.

  • You can also use if-else to break or continue the loop.

Acess the item and index at the same time

1
2
3
4
5
6
7
8
9
10
11
for (const item of restaurant.starterMenu.entries()) console.log(item);
//(2) [0, 'Focaccia']
//(2) [1, 'Bruschetta']
//(2) [2, 'Garlic Bread']
//(2) [3, 'Caprese Salad']
for (const index in restaurant.starterMenu)
console.log(restaurant.starterMenu[index], index);
//Focaccia 0
//Bruschetta 1
//Garlic Bread 2
//Caprese Salad 3

So you can see we used entries()method in for-of loop

entries()

  1. An Array Iterator
1
2
console.log(...restaurant.starterMenu.entries());
//(2) [0, 'Focaccia'] (2) [1, 'Bruschetta'] (2) [2, 'Garlic Bread'] (2) [3, 'Caprese Salad']
  1. Object.entries(objectName)
1
2
console.log(Object.entries(restaurant));
//(6) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2)]

Each Array is composed of the key and the value.

If you want to loop a object

Object.keys(objectName)

This method returns an Arrary composed by the object’s property names.

1
2
console.log(Object.keys(restaurant));
//(6) ['name', 'location', 'categories', 'starterMenu', 'mainMenu', 'openingHours']

Object.values(objectName)

This method returns an Arrary composed by the object’s property values.

1
2
console.log(Object.values(restaurant));
//(6) ['Classico Italiano', 'Via Angelo Tavanti 23, Firenze, Italy', Array(4), Array(4), Array(3), {…}]

本站由 @Eureka 使用 Stellar 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。