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
+51-50Lines changed: 51 additions & 50 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -462,9 +462,9 @@ arr.sort( (a, b) => a - b );
462
462
463
463
### reverse
464
464
465
-
The method [arr.reverse](mdn:js/Array/reverse)reverses the order of elements in`arr`.
465
+
Метод [arr.reverse](mdn:js/Array/reverse)меняет порядок элементов в`arr`.
466
466
467
-
For instance:
467
+
Например:
468
468
469
469
```js run
470
470
let arr = [1, 2, 3, 4, 5];
@@ -473,47 +473,47 @@ arr.reverse();
473
473
alert( arr ); // 5,4,3,2,1
474
474
```
475
475
476
-
It also returns the array `arr`after the reversal.
476
+
Он также возвращает массив `arr`с изменённым порядком элементов.
477
477
478
-
### split and join
478
+
### split и join
479
479
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
+
Ситуация из реальной жизни. Мы пишем сервис отсылки сообщений и посетитель вводит имена тех, кому его отправить: `Вася, Петя, Маша`. Но нам-то гораздо удобнее работать с массивом имен, чем с одной строкой. Как это сделать?
481
481
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`.
483
483
484
-
In the example below, we split by a comma followed by space:
484
+
В примере ниже таким разделителем является строка из запятой и пробела.
485
485
486
486
```js run
487
-
let names ='Bilbo, Gandalf, Nazgul';
487
+
let names ='Вася, Петя, Маша';
488
488
489
489
let arr =names.split(', ');
490
490
491
491
for (let name of arr) {
492
-
alert( `A message to ${name}.` ); //A message to Bilbo (and other names)
492
+
alert( `Вам сообщение ${name}.` ); //Вам сообщение Вася (и другие имена)
493
493
}
494
494
```
495
495
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`есть необязательный второй числовой аргумент -- ограничение на количество элементов в массиве. Если их больше, чем указано – остаток массива будет отброшен. На практике это редко используется:
497
497
498
498
```js run
499
499
let arr ='Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2);
500
500
501
501
alert(arr); // Bilbo, Gandalf
502
502
```
503
503
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` разбил бы строку на массив букв:
506
506
507
507
```js run
508
-
let str = "test";
508
+
let str = "тест";
509
509
510
-
alert( str.split('') ); // t,e,s,t
510
+
alert( str.split('') ); // т,е,с,т
511
511
```
512
512
````
513
513
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`как разделитель.
When we need to iterate over an array -- we can use`forEach`,`for`or`for..of`.
528
+
Если нам нужно перебрать массив -- мы можем использовать`forEach`,`for`или`for..of`.
529
529
530
-
When we need to iterate and return the data for each element -- we can use`map`.
530
+
Если нам нужно перебрать массив и возвратить данные для каждого элемента -- мы используем`map`.
531
531
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
+
Они используются для вычисления на основе массива какого-нибудь единого значения.
533
534
534
-
The syntax is:
535
+
Синтаксис:
535
536
536
537
```js
537
538
let value =arr.reduce(function(previousValue, item, index, array) {
538
539
// ...
539
540
}, initial);
540
541
```
541
542
542
-
The function is applied to the elements. You may notice the familiar arguments, starting from the 2nd:
543
+
К каждому элементу применяется функция. Аргументы, начиная со второго, уже знакомы нам:
543
544
544
-
-`item` -- is the current array item.
545
-
-`index` -- is its position.
546
-
-`array` -- is the array.
545
+
-`item` -- текущий элемент массива.
546
+
-`index` -- его позиция.
547
+
-`array` -- сам массив.
547
548
548
-
So far, like `forEach/map`. But there's one more argument:
549
+
Не так давно мы видели их в `forEach / map`. Но есть еще один аргумент:
549
550
550
-
-`previousValue` -- is the result of the previous function call, `initial`for the first call.
551
+
-`previousValue` -- это результат предыдущего вызова функции, а `initial`нужен для первого вызова.
551
552
552
-
The easiest way to grasp that is by example.
553
+
Этот метод проще всего понять, рассмотрев пример.
553
554
554
-
Here we get a sum of array in one line:
555
+
Тут мы получим сумму всех элементов массива всего одной строкой:
555
556
556
557
```js run
557
558
let arr = [1, 2, 3, 4, 5];
@@ -561,62 +562,62 @@ let result = arr.reduce((sum, current) => sum + current, 0);
561
562
alert(result); // 15
562
563
```
563
564
564
-
Here we used the most common variant of `reduce` which uses only 2 arguments.
565
+
Здесь мы использовали наиболее распространенный вариант `reduce`, который использует только 2 аргумента.
565
566
566
-
Let's see the details of what's going on.
567
+
Давайте детальнее разберём как это работает.
567
568
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`, к которому мы добавлем следующий элемент, и так далее...
571
572
572
-
The calculation flow:
573
+
Поток вычислений получается такой:
573
574
574
575

575
576
576
-
Or in the form of a table, where each row represents a function call on the next array element:
577
+
В виде таблицы где каждая строка – вызов функции на очередном элементе массива:
577
578
578
579
||`sum`|`current`|`result`|
579
580
|---|-----|---------|---------|
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`|
585
586
586
587
587
-
As we can see, the result of the previous call becomes the first argument of the next one.
588
+
Как видно, результат предыдущего вызова передаётся в первый аргумент следующего.
588
589
589
-
We also can omit the initial value:
590
+
Также мы можем опустить начальное значение:
590
591
591
592
```js run
592
593
let arr = [1, 2, 3, 4, 5];
593
594
594
-
//removed initial value from reduce (no 0)
595
+
//убрано начальное значение (нет 0 в конце)
595
596
let result =arr.reduce((sum, current) => sum + current);
596
597
597
598
alert( result ); // 15
598
599
```
599
600
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` в качестве первого значения берётся первый элемент массива, а перебор стартует со второго.
601
602
602
-
The calculation table is the same as above, minus the first row.
603
+
Таблица вычислений будет такая же, за вычетом первой строки.
603
604
604
-
But such use requires an extreme care. If the array is empty, then `reduce`call without initial value gives an error.
605
+
Но такое использование требует крайней осторожности. Если массив пуст, то вызов `reduce`без начального значения выдаст ошибку.
605
606
606
-
Here's an example:
607
+
Вот пример:
607
608
608
609
```js run
609
610
let arr = [];
610
611
611
612
// 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 вернул бы его для пустого массива.
613
614
arr.reduce((sum, current) => sum + current);
614
615
```
615
616
616
617
617
-
So it's advised to always specify the initial value.
618
+
Поэтому рекомендуется всегда указывать начальное значение.
618
619
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)работает аналогично, но идёт по массиву справа-налево.
0 commit comments