You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/05-data-types/05-array-methods/article.md
+50-49Lines changed: 50 additions & 49 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -622,42 +622,42 @@ arr.reduce((sum, current) => sum + current);
622
622
623
623
## Array.isArray
624
624
625
-
Arrays do not form a separate language type. They are based on objects.
625
+
Массивы не образуют отдельный тип языка. Они основаны на объектах.
626
626
627
-
So`typeof`does not help to distinguish a plain object from an array:
627
+
Поэтому`typeof`не может отличить простой объект от массива:
628
628
629
629
```js run
630
-
alert(typeof {}); //object
631
-
alert(typeof []); //same
630
+
alert(typeof {}); //объект
631
+
alert(typeof []); //то же объект
632
632
```
633
633
634
-
...But arrays are used so often that there's a special method for that: [Array.isArray(value)](mdn:js/Array/isArray). It returns`true` if the `value`is an array, and`false`otherwise.
634
+
...Но массивы используются насколько часто, что для этого придумали специальный метод: [Array.isArray(value)](mdn:js/Array/isArray). Он возвращает`true`, если`value`массив, и`false`если нет.
635
635
636
636
```js run
637
637
alert(Array.isArray({})); // false
638
638
639
639
alert(Array.isArray([])); // true
640
640
```
641
641
642
-
## Most methods support "thisArg"
642
+
## Большинство методов поддерживают "thisArg"
643
643
644
-
Almost all array methods that call functions -- like `find`, `filter`, `map`, with a notable exception of `sort`, accept an optional additional parameter`thisArg`.
644
+
Почти все методы массива, которые вызывают функции -- такие как `find`, `filter`, `map`, за исключением метода `sort`, принимают необязательный параметр`thisArg`.
645
645
646
-
That parameter is not explained in the sections above, because it's rarely used. But for completeness we have to cover it.
646
+
Этот параметр не объяснялся выше, так как очень редко используется, но для наиболее полного понимания темы мы обязаны его рассмотреть.
647
647
648
-
Here's the full syntax of these methods:
648
+
Вот полный синтаксис этих методов:
649
649
650
650
```js
651
651
arr.find(func, thisArg);
652
652
arr.filter(func, thisArg);
653
653
arr.map(func, thisArg);
654
654
// ...
655
-
// thisArg is the optional last argument
655
+
// thisArg - это необязательный последний аргумент
656
656
```
657
657
658
-
The value of `thisArg`parameter becomes `this`for`func`.
658
+
Значение параметра `thisArg`становится `this`для`func`.
659
659
660
-
For instance, here we use an object method as a filter and `thisArg`comes in handy:
660
+
Например, вот тут мы используем метод объекта как фильтр и `thisArg`нам очень поможет:
661
661
662
662
```js run
663
663
let user = {
@@ -674,63 +674,64 @@ let users = [
674
674
];
675
675
676
676
*!*
677
-
//find all users younger than user
677
+
//найти всех пользователей моложе чем заданный
678
678
let youngerUsers =users.filter(user.younger, user);
679
679
*/!*
680
680
681
681
alert(youngerUsers.length); // 2
682
682
```
683
683
684
-
In the call above, we use `user.younger` as a filter and also provide `user` as the context for it. If we didn't provide the context, `users.filter(user.younger)` would call `user.younger` as a standalone function, with `this=undefined`. That would mean an instant error.
684
+
В вызове выше, мы используем `user.younger` как фильтр а также отдаём `user` в качестве контекста для него. Если бы мы не предоставляли контекст,
685
+
`users.filter(user.younger)` вызвал бы `user.younger` как отдельную функцию, с `this = undefined`. Это означало бы мгновенную ошибку.
685
686
686
-
## Summary
687
+
## Итого
687
688
688
-
A cheatsheet of array methods:
689
+
Шпаргалка методов массива:
689
690
690
-
-To add/remove elements:
691
-
-`push(...items)` -- adds items to the end,
692
-
-`pop()` -- extracts an item from the end,
693
-
-`shift()` -- extracts an item from the beginning,
694
-
-`unshift(...items)` -- adds items to the beginning.
695
-
-`splice(pos, deleteCount, ...items)` -- at index`pos`delete `deleteCount`elements and insert`items`.
696
-
-`slice(start, end)` -- creates a new array, copies elements from position `start`till`end` (not inclusive) into it.
697
-
-`concat(...items)` -- returns a new array: copies all members of the current one and adds`items` to it. If any of`items`is an array, then its elements are taken.
691
+
-Для добавления/удаления элементов:
692
+
-`push(...items)` -- добавляет элементы в конец,
693
+
-`pop()` -- извлекает элемент с конца,
694
+
-`shift()` -- извлекает элемент с начала,
695
+
-`unshift(...items)` -- добавляет элементы в начало.
696
+
-`splice(pos, deleteCount, ...items)` -- по индексу`pos`удаляет`deleteCount`элементы и вставляет`items`.
697
+
-`slice(start, end)` -- создает новый массив, копируя в него элементы с позиции `start`до`end` (не включая `end`).
698
+
-`concat(...items)` -- возвращает новый массив: копирует все члены текущего массива и добавляет к нему`items`. Если какой-либо из`items`является массивом, тогда берутся его элементы.
698
699
699
-
-To search among elements:
700
-
-`indexOf/lastIndexOf(item, pos)` -- look for `item` starting from position`pos`, return the index or `-1`if not found.
701
-
-`includes(value)` -- returns`true` if the array has `value`, otherwise`false`.
702
-
-`find/filter(func)` -- filter elements through the function, return first/all values that make it return`true`.
703
-
-`findIndex`is like`find`, but returns the index instead of a value.
700
+
-Для поиска среди элементов:
701
+
-`indexOf/lastIndexOf(item, pos)` -- ищет `item`, начиная с позиции`pos` и возвращает его индекс, или `-1`если ничего не найдено.
702
+
-`includes(value)` -- возвращает`true`, если массив имеет значение`value`, в противном случае`false`.
703
+
-`find/filter(func)` -- фильтрует элементы через функцию и отдаёт первые/все значения, которые при прохождении через неё возвращают`true`.
704
+
-`findIndex`похож на`find`, но возвращает индекс вместо значения.
704
705
705
-
-To iterate over elements:
706
-
-`forEach(func)` -- calls`func`for every element, does not return anything.
706
+
-Для перебора элементов:
707
+
-`forEach(func)` -- вызывает`func`для каждого элемента. Ничего не возвращает.
707
708
708
-
-To transform the array:
709
-
-`map(func)` -- creates a new array from results of calling `func`for every element.
710
-
-`sort(func)` -- sorts the array in-place, then returns it.
711
-
-`reverse()` -- reverses the array in-place, then returns it.
712
-
-`split/join` -- convert a string to array and back.
713
-
-`reduce(func, initial)` -- calculate a single value over the array by calling `func`for each element and passing an intermediate result between the calls.
709
+
-Для преобразования массива:
710
+
-`map(func)` -- создаёт новый массив из результатоы вызова `func`для каждого элемента.
711
+
-`sort(func)` -- сортирует массив на месте, а потом возвращает его.
712
+
-`reverse()` -- инвертирует массив на месте, а потом возвращает его.
713
+
-`split/join` -- преобразует строку в массив и обратно.
714
+
-`reduce(func, initial)` -- вычисляет одно значение из всего массива, вызывая `func`для каждого элемента и передавая промежуточный результат между вызовами.
714
715
715
-
-Additionally:
716
-
-`Array.isArray(arr)`checks `arr`for being an array.
716
+
-Дополнительно:
717
+
-`Array.isArray(arr)`проверяет является ли `arr`массивом.
717
718
718
-
Please note that methods`sort`,`reverse`and`splice`modify the array itself.
719
+
Обратите внимание, что методы`sort`,`reverse`и`splice`изменяют исходный массив.
719
720
720
-
These methods are the most used ones, they cover 99% of use cases. But there are few others:
721
+
Изученных нами методов достаточно в 99% случаях, но существуют и другие.
721
722
722
-
-[arr.some(fn)](mdn:js/Array/some)/[arr.every(fn)](mdn:js/Array/every)checks the array.
The function `fn`is called on each element of the array similar to `map`. If any/all results are`true`, returns `true`, otherwise`false`.
725
+
Функция `fn`вызывается для каждого элемента массива аналогично `map`. Если какие-либо/все результаты являются`true`, он возвращает`true`, иначе`false`.
725
726
726
-
-[arr.fill(value, start, end)](mdn:js/Array/fill) -- fills the array with repeating `value`from index `start`to`end`.
-[arr.copyWithin(target, start, end)](mdn:js/Array/copyWithin) -- copies its elements from position`start`till position`end`into *itself*, at position `target` (overwrites existing).
729
+
-[arr.copyWithin(target, start, end)](mdn:js/Array/copyWithin) -- копирует свои элементы начиная со`start`и заканчивая`end`в *собственную*, позицию `target` (перезаписывает существующие).
729
730
730
-
For the full list, see the [manual](mdn:js/Array).
731
+
Полный список см. в [руководстве](mdn:js/Array).
731
732
732
-
From the first sight it may seem that there are so many methods, quite difficult to remember. But actually that's much easier than it seems.
733
+
На первый взгляд может показаться, что существует очень много разных методов, которые довольно сложно запомнить. Но на самом деле это гораздо проще, чем кажется.
733
734
734
-
Look through the cheatsheet just to be aware of them. Then solve the tasks of this chapter to practice, so that you have experience with array methods.
735
+
Поближе ознакомьтесь со шпаргалкой представленной выше, а затем, чтобы попрактиковаться, решите задачи предложенные в данной главе. Так вы получите необходимый опыт в правильном использовании методов массива.
735
736
736
-
Afterwards whenever you need to do something with an array, and you don't know how -- come here, look at the cheatsheet and find the right method. Examples will help you to write it correctly. Soon you'll automatically remember the methods, without specific efforts from your side.
737
+
Всякий раз, когда вам нужно что-то сделать с массивом, и вы не знаете, как это сделать -- приходите сюда, посмотрите на таблицу и найдите правильный метод. Примеры помогут вам всё сделать правильно и вскоре вы автоматически запомните методы без особых усилий с вашей стороны.
0 commit comments