Skip to content

Commit 9733b74

Browse files
committed
1-js/05-data-types/05-array-methods/
Ru translation / + Intro and the splice block was translated
1 parent 7d4702d commit 9733b74

1 file changed

Lines changed: 49 additions & 47 deletions

File tree

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

Lines changed: 49 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,118 +1,120 @@
1-
# Array methods
1+
# Методы массивов
22

3-
Arrays provide a lot of methods. To make things easier, in this chapter they are split into groups.
3+
Массивы предоставляют множество методов. Чтобы было проще, в этой главе они разбиты на группы.
44

5-
## Add/remove items
5+
## Добавление/удаление элементов
66

7-
We already know methods that add and remove items from the beginning or the end:
7+
Мы уже знаем методы, которые добавляют и удаляют элементы из начала или конца:
88

9-
- `arr.push(...items)` -- adds items to the end,
10-
- `arr.pop()` -- extracts an item from the end,
11-
- `arr.shift()` -- extracts an item from the beginning,
12-
- `arr.unshift(...items)` -- adds items to the beginning.
9+
- `arr.push(...items)` -- добавляет элементы в конец,
10+
- `arr.pop()` -- извлекает элемент из конца,
11+
- `arr.shift()` -- извлекает элемент из начала,
12+
- `arr.unshift(...items)` -- добавляет элементы в начало.
1313

14-
Here are few others.
14+
Есть и другие.
1515

16-
### splice
16+
### Метод splice
1717

18-
How to delete an element from the array?
18+
Как удалить элемент из массива?
1919

20-
The arrays are objects, so we can try to use `delete`:
20+
Так как массивы являются объектами, то для удаления ключа можно воспользоваться обычным `delete`:
2121

2222
```js run
2323
let arr = ["I", "go", "home"];
2424

25-
delete arr[1]; // remove "go"
25+
delete arr[1]; // удаляем "go"
2626

2727
alert( arr[1] ); // undefined
2828

29-
// now arr = ["I", , "home"];
29+
// теперь arr = ["I", , "home"];
3030
alert( arr.length ); // 3
3131
```
3232

33-
The element was removed, but the array still has 3 elements, we can see that `arr.length == 3`.
33+
Вроде бы элемент был удалён, но при проверке оказывается что массив всё ещё имеет 3 элемента `arr.length == 3`.
3434

35-
That's natural, because `delete obj.key` removes a value by the `key`. It's all it does. Fine for objects. But for arrays we usually want the rest of elements to shift and occupy the freed place. We expect to have a shorter array now.
35+
Это нормально, потому что всё что делает `delete obj.key`, это удаляет значение с помощью `key`.
36+
Это подходит для объектов, но для массивов мы обычно хотим, чтобы остальные элементы смещались и занимали освободившееся место.
37+
Мы ожидаем, что массив станет короче.
3638

37-
So, special methods should be used.
39+
Для этого нужно использовать специальные методы.
3840

39-
The [arr.splice(str)](mdn:js/Array/splice) method is a swiss army knife for arrays. It can do everything: add, remove and insert elements.
41+
??? Метод [arr.splice(str)](mdn:js/Array/splice) – это универсальный раскладной нож для работы с массивами. Умеет все: добавлять, удалять и заменять элементы.
4042

41-
The syntax is:
43+
Его синтаксис:
4244

4345
```js
4446
arr.splice(index[, deleteCount, elem1, ..., elemN])
4547
```
4648

47-
It starts from the position `index`: removes `deleteCount` elements and then inserts `elem1, ..., elemN` at their place. Returns the array of removed elements.
49+
Удалить `deleteCount` элементов, начиная с номера `index`, а затем вставить `elem1, ..., elemN` на их место. Возвращает массив из удалённых элементов.
4850

49-
This method is easy to grasp by examples.
51+
Этот метод проще всего понять, рассмотрев примеры.
5052

51-
Let's start with the deletion:
53+
Начнём с удаления:
5254

5355
```js run
54-
let arr = ["I", "study", "JavaScript"];
56+
let arr = ["Я", "изучаю", "JavaScript"];
5557

5658
*!*
57-
arr.splice(1, 1); // from index 1 remove 1 element
59+
arr.splice(1, 1); // начиная с позиции 1, удалить 1 элемент
5860
*/!*
5961

60-
alert( arr ); // ["I", "JavaScript"]
62+
alert( arr ); // осталось ["Я", "JavaScript"]
6163
```
6264

63-
Easy, right? Starting from the index `1` it removed `1` element.
65+
Легко, правда? Начиная с позиции `1`, он убрал `1` элемент.
6466

65-
In the next example we remove 3 elements and replace them with the other two:
67+
В следующем примере мы удалим 3 элемента и заменим их двумя другими.
6668

6769
```js run
68-
let arr = [*!*"I", "study", "JavaScript",*/!* "right", "now"];
70+
let arr = [*!*"Я", "изучаю", "JavaScript",*/!* "прямо", "сейчас"];
6971

70-
// remove 3 first elements and replace them with another
71-
arr.splice(0, 3, "Let's", "dance");
72+
// удалить 3 первых елемента и удалить их другими
73+
arr.splice(0, 3, "Давай", "танцевать");
7274

73-
alert( arr ) // now [*!*"Let's", "dance"*/!*, "right", "now"]
75+
alert( arr ) // теперь [*!*"Давай", "танцевать"*/!*, "прямо", "сейчас"]
7476
```
7577

76-
Here we can see that `splice` returns the array of removed elements:
78+
Здесь видно, что splice возвращает массив из удаленных элементов:
7779

7880
```js run
79-
let arr = [*!*"I", "study",*/!* "JavaScript", "right", "now"];
81+
let arr = [*!*"Я", "изучаю",*/!* "JavaScript", "прямо", "сейчас"];
8082

81-
// remove 2 first elements
83+
// удалить 2 первых элемента
8284
let removed = arr.splice(0, 2);
8385

84-
alert( removed ); // "I", "study" <-- array of removed elements
86+
alert( removed ); // "Я", "изучаю" <-- массив из удалённых элементов
8587
```
8688

87-
The `splice` method is also able to insert the elements without any removals. For that we need to set `deleteCount` to `0`:
89+
Метод `splice` также может вставлять элементы без удаления, для этого достаточно установить `deleteCount` в `0`:
8890

8991
```js run
90-
let arr = ["I", "study", "JavaScript"];
92+
let arr = ["Я", "изучаю", "JavaScript"];
9193

92-
// from index 2
93-
// delete 0
94-
// then insert "complex" and "language"
95-
arr.splice(2, 0, "complex", "language");
94+
// с позиции 2
95+
// удалить 0
96+
// вставить "сложный", "язык"
97+
arr.splice(2, 0, "сложный", "язык");
9698

97-
alert( arr ); // "I", "study", "complex", "language", "JavaScript"
99+
alert( arr ); // "Я", "изучаю", "сложный", "язык", "JavaScript"
98100
```
99101

100102
````smart header="Negative indexes allowed"
101-
Here and in other array methods, negative indexes are allowed. They specify the position from the end of the array, like here:
103+
В этом и вдругих методах для массивов допускается использование отрицательного номера позиции, которая в этом случае отсчитывает элементы с конца:
102104
103105
```js run
104106
let arr = [1, 2, 5];
105107
106-
// from index -1 (one step from the end)
107-
// delete 0 elements,
108-
// then insert 3 and 4
108+
// начиная с позиции индексом -1 (перед последним элементом)
109+
// удалить 0 элементов,
110+
// затем вставить числа 3 и 4
109111
arr.splice(-1, 0, 3, 4);
110112
111113
alert( arr ); // 1,2,3,4,5
112114
```
113115
````
114116

115-
### slice
117+
### Метод slice
116118

117119
The method [arr.slice](mdn:js/Array/slice) is much simpler than similar-looking `arr.splice`.
118120

0 commit comments

Comments
 (0)