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
The result of the function (if it returns any) is thrown away and ignored.
233
+
Результат функции (если она что-то возвращает) отбрасывается и игнорируется.
235
234
236
235
237
-
## Searching in array
236
+
## Поиск в массиве
238
237
239
-
These are methods to search for something in an array.
238
+
Это методы поиска чего-либо в массиве.
240
239
241
-
### indexOf/lastIndexOf and includes
240
+
### indexOf/lastIndexOf и includes
242
241
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)имеют одинаковый синтаксис и делают по сути то же самое что и их строковые аналоги, но работают с элементами вместо символов:
244
243
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`, если найдёт.
Note that the methods use `===` comparison. So, if we look for `false`, it finds exactly`false` and not the zero.
260
+
Обратите внимание, что методы используют сравнение `===`. Таким образом, если мы ищем `false`, он находит именно`false`, а не ноль.
262
261
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`.
264
263
265
-
Also, a very minor difference of `includes` is that it correctly handles `NaN`, unlike `indexOf/lastIndexOf`:
264
+
Кроме того, очень незначительным отличием `include` является то, что он правильно обрабатывает`NaN`, в отличие от `indexOf / lastIndexOf`:
266
265
267
266
```js run
268
267
constarr= [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 (верно)
271
270
```
272
271
273
-
### find and findIndex
272
+
### find и findIndex
274
273
275
-
Imagine we have an array of objects. How do we find an object with the specific condition?
274
+
Представьте, что у нас есть массив объектов. Как нам найти объект с определенным условием?
276
275
277
-
Here the [arr.find](mdn:js/Array/find) method comes in handy.
276
+
Здесь пригодится метод [arr.find](mdn:js/Array/find).
278
277
279
-
The syntax is:
278
+
Его синтаксис таков:
280
279
```js
281
280
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
284
283
});
285
284
```
286
285
287
-
The function is called repetitively for each element of the array:
286
+
Функция вызывается многократно для каждого элемента массива:
288
287
289
-
-`item`is the element.
290
-
-`index`is its index.
291
-
-`array`is the array itself.
288
+
-`item`это элемент.
289
+
-`index`это его индекс.
290
+
-`array`это сам массив.
292
291
293
-
If it returns`true`, the search is stopped, the`item` is returned. If nothing found, `undefined` is returned.
292
+
Если функция возвращает`true`, поиск останавливается, возвращается`item`. Если ничего не найдено, возвращается `undefined`.
294
293
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`:
296
295
297
296
```js run
298
297
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:"Маша"}
302
301
];
303
302
304
303
let user =users.find(item=>item.id==1);
305
304
306
-
alert(user.name); //John
305
+
alert(user.name); //Вася
307
306
```
308
307
309
-
In real life arrays of objects is a common thing, so the`find`method is very useful.
308
+
В реальной жизни массивы объектов обычное дело, поэтому метод`find`очень полезен.
310
309
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`с одним аргументом. Другие аргументы этой функции используются редко.
312
311
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`, когда ничего не найдено.
0 commit comments