Blog/content/posts/2022/javascript/foreach.md
2022-11-19 03:36:06 +03:00

61 lines
1.4 KiB
Markdown

---
title: "🗃️ Перебор элементов в JavaScript"
date: 2022-11-02T23:52:56+03:00
draft: false
tags: [javascript, development, tutorial]
---
## Массивы
Синтаксис:
```javascript
arr.forEach(function callback(currentValue, index, array) {
//your iterator
}[, thisArg]);
```
Пример:
```javascript
let exampleArray = [
{name: 'Alex', age: 15},
{name: 'Regina', age: 21},
];
exampleArray.forEach((value, index) => {
console.log(`${index} - ${value.name}: ${value.age}`);
});
```
[Documentation on Developer.Mozilla](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
## Объекты
Синтаксис:
```javascript
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});
```
Пример:
```javascript
let Buttons = {
up: {x: 0, y: 10, pressed: false, callback: 'fButtonUp'},
down: {x: 0, y: 0, pressed: false, callback: 'fButtonDown'},
start: {x: 150, y: 50, pressed: false, callback: 'fButtonStart'},
};
Object.entries(Buttons).forEach(([key, value]) => {
console.log(key, value.pressed);
console.log(`Pos: ${Buttons[key].x}x${Buttons[key].y}`);
console.log();
console.log();
});
```
[Documentation on Developer.Mozilla](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)