Skip to content

Commit d80d7bc

Browse files
committed
1-js/05-data-types/05-array-methods/
Ru translation: Concat, forEach, indexOf/lastIndexOf/includes, find and findIndex blocks of text have been translated
1 parent d7a8490 commit d80d7bc

1 file changed

Lines changed: 60 additions & 61 deletions

File tree

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

Lines changed: 60 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
Есть и другие.
1515

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

1818
Как удалить элемент из массива?
1919

@@ -22,7 +22,7 @@
2222
```js run
2323
let arr = ["I", "go", "home"];
2424

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

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

@@ -100,12 +100,12 @@ alert( arr ); // "Я", "изучаю", "сложный", "язык", "JavaScript
100100
```
101101

102102
````smart header="Negative indexes allowed"
103-
В этом и вдругих методах для массивов допускается использование отрицательного номера позиции, которая в этом случае отсчитывает элементы с конца:
103+
В этом и в других методах для массивов допускается использование отрицательного номера позиции, которая в этом случае отсчитывает элементы с конца:
104104
105105
```js run
106106
let arr = [1, 2, 5];
107107
108-
// начиная с позиции индексом -1 (перед последним элементом)
108+
// начиная с индекса -1 (перед последним элементом)
109109
// удалить 0 элементов,
110110
// затем вставить числа 3 и 4
111111
arr.splice(-1, 0, 3, 4);
@@ -114,7 +114,7 @@ alert( arr ); // 1,2,3,4,5
114114
```
115115
````
116116

117-
### Метод slice
117+
### slice
118118

119119
Метод [arr.slice](mdn:js/Array/slice) намного проще чем похожий на него `arr.splice`
120120

@@ -142,7 +142,7 @@ alert( str.slice(-2) ); // st
142142
alert( arr.slice(-2) ); // s,t
143143
```
144144

145-
### Метод concat
145+
### concat
146146

147147
Метод [arr.concat](mdn:js/Array/concat) объединяет массив с другими массивами и/или элементами.
148148

@@ -152,101 +152,100 @@ alert( arr.slice(-2) ); // s,t
152152
arr.concat(arg1, arg2...)
153153
```
154154

155-
It accepts any number of arguments -- either arrays or values.
156-
Он принимает любое количество аргументов - которые могут быть массивами и значениями.
155+
Он принимает любое количество аргументов -- которые могут быть массивами или значениями.
157156

158-
The result is a new array containing items from `arr`, then `arg1`, `arg2` etc.
157+
В результате мы получаем новый массив включающий в себя элементы из `arr`, а также `arg1`, `arg2` и так далее...
159158

160-
If an argument is an array or has `Symbol.isConcatSpreadable` property, then all its elements are copied. Otherwise, the argument itself is copied.
159+
Если аргумент — массив, или имеет свойство `Symbol.isConcatSpreadable`, то все его элементы копируются. В противном случае скопируется сам аргумент.
161160

162-
For instance:
161+
Например:
163162

164163
```js run
165164
let arr = [1, 2];
166165

167-
// merge arr with [3,4]
166+
// объеденить arr с [3,4]
168167
alert( arr.concat([3, 4])); // 1,2,3,4
169168

170-
// merge arr with [3,4] and [5,6]
169+
// объеденить arr с [3,4] и [5,6]
171170
alert( arr.concat([3, 4], [5, 6])); // 1,2,3,4,5,6
172171

173-
// merge arr with [3,4], then add values 5 and 6
172+
// объеденить arr с [3,4], потом добавить значение 5 и 6
174173
alert( arr.concat([3, 4], 5, 6)); // 1,2,3,4,5,6
175174
```
176175

177-
Normally, it only copies elements from arrays ("spreads" them). Other objects, even if they look like arrays, added as a whole:
176+
Как правило, он только копирует элементы из массивов («раскладывает» их). Другие объекты, даже если они выглядят как массивы, добавляются как есть:
178177

179178
```js run
180179
let arr = [1, 2];
181180

182181
let arrayLike = {
183-
0: "something",
182+
0: "что-то",
184183
length: 1
185184
};
186185

187186
alert( arr.concat(arrayLike) ); // 1,2,[object Object]
188187
//[1, 2, arrayLike]
189188
```
190189

191-
...But if an array-like object has `Symbol.isConcatSpreadable` property, then its elements are added instead:
190+
... Но если массивоподобный объект имеет свойство `Symbol.isConcatSpreadable`, вместо него добавляются его элементы:
192191

193192
```js run
194193
let arr = [1, 2];
195194

196195
let arrayLike = {
197-
0: "something",
198-
1: "else",
196+
0: "что-то",
197+
1: "ещё",
199198
*!*
200199
[Symbol.isConcatSpreadable]: true,
201200
*/!*
202201
length: 2
203202
};
204203

205-
alert( arr.concat(arrayLike) ); // 1,2,something,else
204+
alert( arr.concat(arrayLike) ); // 1,2,что-то,ещё
206205
```
207206

208-
## Iterate: forEach
207+
## Перебор: forEach
209208

210-
The [arr.forEach](mdn:js/Array/forEach) method allows to run a function for every element of the array.
209+
Метод [arr.forEach](mdn:js/Array/forEach) позволяет запускать функцию для каждого элемента массива.
211210

212-
The syntax:
211+
Его синтаксис:
213212
```js
214213
arr.forEach(function(item, index, array) {
215-
// ... do something with item
214+
// ... делать что-то с item
216215
});
217216
```
218217

219-
For instance, this shows each element of the array:
218+
Например этот код покажет каждый элемент массива:
220219

221220
```js run
222-
// for each element call alert
221+
// Вызов alert для каждого элемента
223222
["Bilbo", "Gandalf", "Nazgul"].forEach(alert);
224223
```
225224

226-
And this code is more elaborate about their positions in the target array:
225+
А этот более подробно опишет их позиции в заданном массиве:
227226

228227
```js run
229228
["Bilbo", "Gandalf", "Nazgul"].forEach((item, index, array) => {
230-
alert(`${item} is at index ${index} in ${array}`);
229+
alert(`${item} имеет позицию ${index} в ${array}`);
231230
});
232231
```
233232

234-
The result of the function (if it returns any) is thrown away and ignored.
233+
Результат функции (если она что-то возвращает) отбрасывается и игнорируется.
235234

236235

237-
## Searching in array
236+
## Поиск в массиве
238237

239-
These are methods to search for something in an array.
238+
Это методы поиска чего-либо в массиве.
240239

241-
### indexOf/lastIndexOf and includes
240+
### indexOf/lastIndexOf и includes
242241

243-
The methods [arr.indexOf](mdn:js/Array/indexOf), [arr.lastIndexOf](mdn:js/Array/lastIndexOf) and [arr.includes](mdn:js/Array/includes) have the same syntax and do essentially the same as their string counterparts, but operate on items instead of characters:
242+
Методы [arr.indexOf](mdn:js/Array/indexOf), [arr.lastIndexOf](mdn:js/Array/lastIndexOf) и [arr.includes](mdn:js/Array/includes) имеют одинаковый синтаксис и делают по сути то же самое что и их строковые аналоги, но работают с элементами вместо символов:
244243

245-
- `arr.indexOf(item, from)` looks for `item` starting from index `from`, and returns the index where it was found, otherwise `-1`.
246-
- `arr.lastIndexOf(item, from)` -- same, but looks from right to left.
247-
- `arr.includes(item, from)` -- looks for `item` starting from index `from`, returns `true` if found.
244+
- `arr.indexOf (item, from)` ищет `item`, начиная с индекса` from`, и возвращает индекс, в котором он был найден, в противном случае `-1`.
245+
- `arr.lastIndexOf (item, from)` - то же самое, но ищет справа налево.
246+
- `arr.includes (item, from)` - ищет `item`, начиная с индекса` from`, возвращает `true`, если найдёт.
248247

249-
For instance:
248+
Например:
250249

251250
```js run
252251
let arr = [1, 0, false];
@@ -258,59 +257,59 @@ alert( arr.indexOf(null) ); // -1
258257
alert( arr.includes(1) ); // true
259258
```
260259

261-
Note that the methods use `===` comparison. So, if we look for `false`, it finds exactly `false` and not the zero.
260+
Обратите внимание, что методы используют сравнение `===`. Таким образом, если мы ищем `false`, он находит именно `false`, а не ноль.
262261

263-
If we want to check for inclusion, and don't want to know the exact index, then `arr.includes` is preferred.
262+
Если мы хотим проверить наличие включений и не хотим знать точный индекс, тогда предпочтительным является `arr.include`.
264263

265-
Also, a very minor difference of `includes` is that it correctly handles `NaN`, unlike `indexOf/lastIndexOf`:
264+
Кроме того, очень незначительным отличием `include` является то, что он правильно обрабатывает` NaN`, в отличие от `indexOf / lastIndexOf`:
266265

267266
```js run
268267
const arr = [NaN];
269-
alert( arr.indexOf(NaN) ); // -1 (should be 0, but === equality doesn't work for NaN)
270-
alert( arr.includes(NaN) );// true (correct)
268+
alert( arr.indexOf(NaN) ); // -1 (должен быть 0, но === равенство не работает для NaN)
269+
alert( arr.includes(NaN) );// true (верно)
271270
```
272271

273-
### find and findIndex
272+
### find и findIndex
274273

275-
Imagine we have an array of objects. How do we find an object with the specific condition?
274+
Представьте, что у нас есть массив объектов. Как нам найти объект с определенным условием?
276275

277-
Here the [arr.find](mdn:js/Array/find) method comes in handy.
276+
Здесь пригодится метод [arr.find](mdn:js/Array/find).
278277

279-
The syntax is:
278+
Его синтаксис таков:
280279
```js
281280
let result = arr.find(function(item, index, array) {
282-
// if true is returned, item is returned and iteration is stopped
283-
// for falsy scenario returns undefined
281+
// если возвращается true, метод возвращает элемент и итерация останавливается
282+
// для ложного сценария возвращает undefined
284283
});
285284
```
286285

287-
The function is called repetitively for each element of the array:
286+
Функция вызывается многократно для каждого элемента массива:
288287

289-
- `item` is the element.
290-
- `index` is its index.
291-
- `array` is the array itself.
288+
- `item` это элемент.
289+
- `index` это его индекс.
290+
- `array` это сам массив.
292291

293-
If it returns `true`, the search is stopped, the `item` is returned. If nothing found, `undefined` is returned.
292+
Если функция возвращает `true`, поиск останавливается, возвращается `item`. Если ничего не найдено, возвращается `undefined`.
294293

295-
For example, we have an array of users, each with the fields `id` and `name`. Let's find the one with `id == 1`:
294+
Например, у нас есть массив пользователей, каждый из которых имеет поля `id` и` name`. Давайте найдем того, кто с `id == 1`:
296295

297296
```js run
298297
let users = [
299-
{id: 1, name: "John"},
300-
{id: 2, name: "Pete"},
301-
{id: 3, name: "Mary"}
298+
{id: 1, name: "Вася"},
299+
{id: 2, name: "Петя"},
300+
{id: 3, name: "Маша"}
302301
];
303302

304303
let user = users.find(item => item.id == 1);
305304

306-
alert(user.name); // John
305+
alert(user.name); // Вася
307306
```
308307

309-
In real life arrays of objects is a common thing, so the `find` method is very useful.
308+
В реальной жизни массивы объектов обычное дело, поэтому метод `find` очень полезен.
310309

311-
Note that in the example we provide to `find` the function `item => item.id == 1` with one argument. Other arguments of this function are rarely used.
310+
Обратите внимание, что в данном примере мы предоставляем `find` функцию` item => item.id == 1` с одним аргументом. Другие аргументы этой функции используются редко.
312311

313-
The [arr.findIndex](mdn:js/Array/findIndex) method is essentially the same, but it returns the index where the element was found instead of the element itself and `-1` is returned when nothing is found.
312+
Метод [arr.findIndex](mdn:js/Array/findIndex) по сути тот же самое, но он возвращает индекс, в на котором был найден элемент, а не сам элемент, и возвращается `-1`, когда ничего не найдено.
314313

315314
### filter
316315

0 commit comments

Comments
 (0)