From 5a741c5a9e7e0e3f4f9b218c1af17bdd12aa5d0f Mon Sep 17 00:00:00 2001 From: Alexander Popov Date: Thu, 3 Nov 2022 00:03:53 +0300 Subject: [PATCH] add js foreach elements --- content/posts/2022/javascript/foreach.md | 60 ++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 content/posts/2022/javascript/foreach.md diff --git a/content/posts/2022/javascript/foreach.md b/content/posts/2022/javascript/foreach.md new file mode 100644 index 0000000..a2430a4 --- /dev/null +++ b/content/posts/2022/javascript/foreach.md @@ -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)