add js foreach elements
This commit is contained in:
parent
78efa6f89e
commit
5a741c5a9e
60
content/posts/2022/javascript/foreach.md
Normal file
60
content/posts/2022/javascript/foreach.md
Normal file
@ -0,0 +1,60 @@
|
||||
---
|
||||
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)
|
Loading…
Reference in New Issue
Block a user