Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Решения задач по методу forEach
- // Задача 1. Обнулить все флаги
- let emails1 = [
- { subject: 'Привет', read: false },
- { subject: 'Счёт', read: false },
- { subject: 'Напоминание', read: false }
- ];
- emails1.forEach(function(mail) {
- mail.read = false;
- });
- console.log(emails1);
- // Задача 2. Перевести цены в копейки
- let prices = [99.5, 150, 200.25];
- let inCents = [];
- prices.forEach(function(price) {
- inCents.push(Math.round(price * 100));
- });
- console.log(inCents); // [9950, 15000, 20025]
- // Задача 3. Подсветить чётные строки
- // Предполагается, что в HTML есть <ul id="list"><li>…</li></ul>
- const nodes = document.querySelectorAll('#list li');
- nodes.forEach(function(li) {
- const n = parseInt(li.textContent, 10);
- if (n % 2 === 0) {
- li.style.backgroundColor = 'yellow';
- }
- });
- // Задача 4. Собрать e‑mail‑адреса
- let users = [
- ];
- let emails = [];
- users.forEach(function(u) {
- emails.push(u.email);
- });
- // Задача 5. Суммарная длина строк
- let words = ['apple','banana','cherry'];
- let totalLength = 0;
- words.forEach(function(w) {
- totalLength += w.length;
- });
- console.log(totalLength); // 16
- // Задача 6. Выделить дубликаты
- let items = [1,2,2,3,3,3];
- let seen = [];
- let dups = [];
- items.forEach(function(v) {
- if (seen.indexOf(v) === -1) {
- seen.push(v);
- } else {
- dups.push(v);
- }
- });
- console.log(dups); // [2,3,3]
- // Задача 7. Маркировка пройденных шагов
- let steps = ['Intro','Basics','Loops','Finish'];
- let completedSteps = [];
- let done = false;
- steps.forEach(function(step) {
- if (!done) {
- completedSteps.push(step);
- if (step === 'Loops') {
- done = true;
- }
- }
- });
- console.log(completedSteps); // ['Intro','Basics','Loops']
- // Задача 8. Обратный порядок без reverse()
- let arr = [1,2,3,4];
- let indices = Array.from(arr.keys()); // [0,1,2,3]
- indices.reverse().forEach(function(i) {
- console.log(arr[i]);
- });
- // Выведет 4,3,2,1
- // Задача 9. Пропустить пустые строки
- let data = ['hello','','world','','!'];
- let nonEmpty = [];
- data.forEach(function(s) {
- if (s !== '') {
- nonEmpty.push(s);
- }
- });
- console.log(nonEmpty); // ['hello','world','!']
- // Задача 10. Обновить каждый объект (добавить fullPrice)
- let products = [
- { name: 'A', price: 100, tax: 0.2 },
- { name: 'B', price: 200, tax: 0.1 }
- ];
- products.forEach(function(p) {
- p.fullPrice = p.price + p.price * p.tax;
- });
- console.log(products);
- // [
- // { name:'A', price:100, tax:0.2, fullPrice:120 },
- // { name:'B', price:200, tax:0.1, fullPrice:220 }
- // ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement