Array methods · Методы массивов
Array methods
.map(fn)makes a new array by transforming each item..filter(fn)makes a new array of only the items wherefnreturnstrue..forEach(fn)runsfnfor each item, making no new array.
Методы массивов
.map(fn)создает новый массив, преобразуя каждый элемент..filter(fn)создает новый массив только из тех элементов, для которыхfnвозвращаетtrue..forEach(fn)выполняетfnдля каждого элемента, не создавая нового массива.
let nums = [1, 2, 3];
let doubled = nums.map((n) => n * 2);
console.log(doubled); // → [2,4,6]
Filtering keeps some items
.filterkeeps each item for which the test returnstrue.
Фильтрация сохраняет некоторые элементы
.filterсохраняет каждый элемент, для которого проверка возвращаетtrue.
let nums = [3, 7, 2, 9];
let big = nums.filter((n) => n > 4);
console.log(big); // → [7,9]
Watch out
.mapand.filterreturn a new array — the original is untouched.- You hand each one an arrow function that says what to do with one item.
Будьте осторожны
.mapи.filterвозвращают новый массив — оригинальный остается нетронутым.- Вы передаете каждому стрелочную функцию, указывающую, что делать с одним элементом.
Common mistakes
mapandfilterreturn a NEW array — they do not change the original.forEachjust loops and returns nothing.
Распространенные ошибки
mapиfilterвозвращают НОВЫЙ массив — они не изменяют исходный.forEachпросто проходит циклом и ничего не возвращает.
Now you try
- Use
.map,.filteror.forEach. - Press Check answer to test it.
Теперь попробуйте сами
- Используйте
.map,.filterили.forEach. - Нажмите Проверить ответ, чтобы протестировать её.
Use .map to double every number in [1, 2, 3] and store the new array in result (it should be [2, 4, 6]). · Используйте .map, чтобы удвоить каждое число в [1, 2, 3] и сохранить новый массив в result (он должен быть равен [2, 4, 6]).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Use .filter to keep only the numbers greater than 4 from [3, 7, 2, 9, 1], in a variable big (it should be [7, 9]). · Используйте .filter, чтобы оставить только числа больше 4 из [3, 7, 2, 9, 1], в переменной big (он должен быть равен [7, 9]).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Use .forEach to add every number in [4, 8, 15] to total (it should end up 27). · Используйте .forEach, чтобы прибавить каждое число из [4, 8, 15] к total (итоговое значение должно получиться 27).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.