Skip to content

Commit c71a107

Browse files
committed
1-js/05-data-types/05-array-methods/
Ru translation: reverse, split, join, reduce blocks of text have been translated
1 parent 2b3bebe commit c71a107

1 file changed

Lines changed: 51 additions & 50 deletions

File tree

1-js/05-data-types/05-array-methods/article.md

Lines changed: 51 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -462,9 +462,9 @@ arr.sort( (a, b) => a - b );
462462

463463
### reverse
464464

465-
The method [arr.reverse](mdn:js/Array/reverse) reverses the order of elements in `arr`.
465+
Метод [arr.reverse](mdn:js/Array/reverse) меняет порядок элементов в `arr`.
466466

467-
For instance:
467+
Например:
468468

469469
```js run
470470
let arr = [1, 2, 3, 4, 5];
@@ -473,47 +473,47 @@ arr.reverse();
473473
alert( arr ); // 5,4,3,2,1
474474
```
475475

476-
It also returns the array `arr` after the reversal.
476+
Он также возвращает массив `arr` с изменённым порядком элементов.
477477

478-
### split and join
478+
### split и join
479479

480-
Here's the situation from the real life. We are writing a messaging app, and the person enters the comma-delimited list of receivers: `John, Pete, Mary`. But for us an array of names would be much more comfortable than a single string. How to get it?
480+
Ситуация из реальной жизни. Мы пишем сервис отсылки сообщений и посетитель вводит имена тех, кому его отправить: `Вася, Петя, Маша`. Но нам-то гораздо удобнее работать с массивом имен, чем с одной строкой. Как это сделать?
481481

482-
The [str.split(delim)](mdn:js/String/split) method does exactly that. It splits the string into an array by the given delimiter `delim`.
482+
Метод [str.split(delim)](mdn:js/String/split) именно это и делает. Он разбивает строку на массив по заданному разделителю `delim`.
483483

484-
In the example below, we split by a comma followed by space:
484+
В примере ниже таким разделителем является строка из запятой и пробела.
485485

486486
```js run
487-
let names = 'Bilbo, Gandalf, Nazgul';
487+
let names = 'Вася, Петя, Маша';
488488

489489
let arr = names.split(', ');
490490

491491
for (let name of arr) {
492-
alert( `A message to ${name}.` ); // A message to Bilbo (and other names)
492+
alert( `Вам сообщение ${name}.` ); // Вам сообщение Вася (и другие имена)
493493
}
494494
```
495495

496-
The `split` method has an optional second numeric argument -- a limit on the array length. If it is provided, then the extra elements are ignored. In practice it is rarely used though:
496+
У метода `split` есть необязательный второй числовой аргумент -- ограничение на количество элементов в массиве. Если их больше, чем указано – остаток массива будет отброшен. На практике это редко используется:
497497

498498
```js run
499499
let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2);
500500

501501
alert(arr); // Bilbo, Gandalf
502502
```
503503

504-
````smart header="Split into letters"
505-
The call to `split(s)` with an empty `s` would split the string into an array of letters:
504+
````smart header="Разбивка по буквам"
505+
Вызов `split(s)` с пустой `s` разбил бы строку на массив букв:
506506
507507
```js run
508-
let str = "test";
508+
let str = "тест";
509509
510-
alert( str.split('') ); // t,e,s,t
510+
alert( str.split('') ); // т,е,с,т
511511
```
512512
````
513513

514-
The call [arr.join(separator)](mdn:js/Array/join) does the reverse to `split`. It creates a string of `arr` items glued by `separator` between them.
514+
Вызов [arr.join(separator)](mdn:js/Array/join) делает в точности противоположное `split`. Он создаёт строку из елементов `arr` используя `separator` как разделитель.
515515

516-
For instance:
516+
Например:
517517

518518
```js run
519519
let arr = ['Bilbo', 'Gandalf', 'Nazgul'];
@@ -525,33 +525,34 @@ alert( str ); // Bilbo;Gandalf;Nazgul
525525

526526
### reduce/reduceRight
527527

528-
When we need to iterate over an array -- we can use `forEach`, `for` or `for..of`.
528+
Если нам нужно перебрать массив -- мы можем использовать `forEach`,` for` или `for..of`.
529529

530-
When we need to iterate and return the data for each element -- we can use `map`.
530+
Если нам нужно перебрать массив и возвратить данные для каждого элемента -- мы используем `map`.
531531

532-
The methods [arr.reduce](mdn:js/Array/reduce) and [arr.reduceRight](mdn:js/Array/reduceRight) also belong to that breed, but are a little bit more intricate. They are used to calculate a single value based on the array.
532+
Методы [arr.reduce](mdn:js/Array/reduce) и [arr.reduceRight](mdn:js/Array/reduceRight) похожы на методы выше, но они немного сложнее.
533+
Они используются для вычисления на основе массива какого-нибудь единого значения.
533534

534-
The syntax is:
535+
Синтаксис:
535536

536537
```js
537538
let value = arr.reduce(function(previousValue, item, index, array) {
538539
// ...
539540
}, initial);
540541
```
541542

542-
The function is applied to the elements. You may notice the familiar arguments, starting from the 2nd:
543+
К каждому элементу применяется функция. Аргументы, начиная со второго, уже знакомы нам:
543544

544-
- `item` -- is the current array item.
545-
- `index` -- is its position.
546-
- `array` -- is the array.
545+
- `item` -- текущий элемент массива.
546+
- `index` -- его позиция.
547+
- `array` -- сам массив.
547548

548-
So far, like `forEach/map`. But there's one more argument:
549+
Не так давно мы видели их в `forEach / map`. Но есть еще один аргумент:
549550

550-
- `previousValue` -- is the result of the previous function call, `initial` for the first call.
551+
- `previousValue` -- это результат предыдущего вызова функции, а `initial` нужен для первого вызова.
551552

552-
The easiest way to grasp that is by example.
553+
Этот метод проще всего понять, рассмотрев пример.
553554

554-
Here we get a sum of array in one line:
555+
Тут мы получим сумму всех элементов массива всего одной строкой:
555556

556557
```js run
557558
let arr = [1, 2, 3, 4, 5];
@@ -561,62 +562,62 @@ let result = arr.reduce((sum, current) => sum + current, 0);
561562
alert(result); // 15
562563
```
563564

564-
Here we used the most common variant of `reduce` which uses only 2 arguments.
565+
Здесь мы использовали наиболее распространенный вариант `reduce`, который использует только 2 аргумента.
565566

566-
Let's see the details of what's going on.
567+
Давайте детальнее разберём как это работает.
567568

568-
1. On the first run, `sum` is the initial value (the last argument of `reduce`), equals `0`, and `current` is the first array element, equals `1`. So the result is `1`.
569-
2. On the second run, `sum = 1`, we add the second array element (`2`) to it and return.
570-
3. On the 3rd run, `sum = 3` and we add one more element to it, and so on...
569+
1. При первом запуске `sum` -- это начальное значение (последний аргумент `reduce`), равен `0`, а `current` -- первый элемент массива, равен `1`. Таким образом, результат равен `1`.
570+
2. При втором запуске, `sum = 1`, и к нему мы добавляем второй элемент массива (`2`).
571+
3. На 3-м запуске, `sum = 3`, к которому мы добавлем следующий элемент, и так далее...
571572

572-
The calculation flow:
573+
Поток вычислений получается такой:
573574

574575
![](reduce.png)
575576

576-
Or in the form of a table, where each row represents a function call on the next array element:
577+
В виде таблицы где каждая строка – вызов функции на очередном элементе массива:
577578

578579
| |`sum`|`current`|`result`|
579580
|---|-----|---------|---------|
580-
|the first call|`0`|`1`|`1`|
581-
|the second call|`1`|`2`|`3`|
582-
|the third call|`3`|`3`|`6`|
583-
|the fourth call|`6`|`4`|`10`|
584-
|the fifth call|`10`|`5`|`15`|
581+
|первый вызов|`0`|`1`|`1`|
582+
|второй вызов|`1`|`2`|`3`|
583+
|третий вызов|`3`|`3`|`6`|
584+
|четвёртый вызов|`6`|`4`|`10`|
585+
|пятый вызов|`10`|`5`|`15`|
585586

586587

587-
As we can see, the result of the previous call becomes the first argument of the next one.
588+
Как видно, результат предыдущего вызова передаётся в первый аргумент следующего.
588589

589-
We also can omit the initial value:
590+
Также мы можем опустить начальное значение:
590591

591592
```js run
592593
let arr = [1, 2, 3, 4, 5];
593594

594-
// removed initial value from reduce (no 0)
595+
// убрано начальное значение (нет 0 в конце)
595596
let result = arr.reduce((sum, current) => sum + current);
596597

597598
alert( result ); // 15
598599
```
599600

600-
The result is the same. That's because if there's no initial, then `reduce` takes the first element of the array as the initial value and starts the iteration from the 2nd element.
601+
Результат – точно такой же! Это потому, что при отсутствии `initial` в качестве первого значения берётся первый элемент массива, а перебор стартует со второго.
601602

602-
The calculation table is the same as above, minus the first row.
603+
Таблица вычислений будет такая же, за вычетом первой строки.
603604

604-
But such use requires an extreme care. If the array is empty, then `reduce` call without initial value gives an error.
605+
Но такое использование требует крайней осторожности. Если массив пуст, то вызов `reduce` без начального значения выдаст ошибку.
605606

606-
Here's an example:
607+
Вот пример:
607608

608609
```js run
609610
let arr = [];
610611

611612
// Error: Reduce of empty array with no initial value
612-
// if the initial value existed, reduce would return it for the empty arr.
613+
// если бы существовало начальное значение, reduce вернул бы его для пустого массива.
613614
arr.reduce((sum, current) => sum + current);
614615
```
615616

616617

617-
So it's advised to always specify the initial value.
618+
Поэтому рекомендуется всегда указывать начальное значение.
618619

619-
The method [arr.reduceRight](mdn:js/Array/reduceRight) does the same, but goes from right to left.
620+
Метод [arr.reduceRight](mdn:js/Array/reduceRight) работает аналогично, но идёт по массиву справа-налево.
620621

621622

622623
## Array.isArray

0 commit comments

Comments
 (0)