1.4 KiB
1.4 KiB
title | date | draft | tags | |||
---|---|---|---|---|---|---|
Перебор элементов в JavaScript | 2022-11-02T23:52:56+03:00 | false |
|
Массивы
Синтаксис:
arr.forEach(function callback(currentValue, index, array) {
//your iterator
}[, thisArg]);
Пример:
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
Объекты
Синтаксис:
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});
Пример:
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();
});