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
A common error experienced by beginning JavaScript developers is that `for...in`for an array does not iterate over the array items. Instead it iterates over the *keys* of the object passed in. This is demonstrated in the below example. Here you would expect `9,2,5` but you get the indexes`0,1,2`:
2
+
Распространенная ошибка, с которой сталкиваются начинающие JavaScript разработчики - это то, что `for...in`для массива не итерирует элементы массива. Вместо этого итерация происходит по *ключам* переданного объекта. Это показано на примере ниже. Здесь мы ожидаем `9,2,5`, но получаем индексы`0,1,2`:
3
3
4
4
```ts
5
5
var someArray = [9, 2, 5];
@@ -8,7 +8,7 @@ for (var item in someArray) {
8
8
}
9
9
```
10
10
11
-
This is one of the reasons why `for...of`exists in TypeScript (and ES6). The following iterates over the array correctly logging out the members as expected:
11
+
Это первая причина, по которой `for...of`существует в TypeScript (и ES6). Следующая итерация массива корректно выводит члены массива как ожидалось:
12
12
13
13
```ts
14
14
var someArray = [9, 2, 5];
@@ -17,7 +17,7 @@ for (var item of someArray) {
17
17
}
18
18
```
19
19
20
-
Similarly TypeScript has no trouble going through a string character by character using`for...of`:
20
+
Точно также TypeScript не испытывает затруднений при итерировании строки посимвольно, используя`for...of`:
21
21
22
22
```ts
23
23
var hello ="is it me you're looking for?";
@@ -26,36 +26,37 @@ for (var char of hello) {
26
26
}
27
27
```
28
28
29
-
#### JS Generation
30
-
For pre ES6 targets TypeScript will generate the standard `for (var i = 0; i < list.length; i++)` kind of loop. For example here's what gets generated for our previous example:
29
+
#### Генерация JS
30
+
Для версий JS до ES6 TypeScript генерирует стандартный тип цикла `for (var i = 0; i < list.length; i++)`. Например, вот что генерируется для нашего предыдущего примера:
31
+
31
32
```ts
32
33
var someArray = [9, 2, 5];
33
34
for (var item ofsomeArray) {
34
35
console.log(item);
35
36
}
36
37
37
-
//becomes //
38
+
//становится //
38
39
39
40
for (var _i =0; _i<someArray.length; _i++) {
40
41
var item =someArray[_i];
41
42
console.log(item);
42
43
}
43
44
```
44
-
You can see that using `for...of`makes *intent* clearer and also decreases the amount of code you have to write (and variable names you need to come up with).
45
+
Вы видите, что использование `for...of`делает код более понятным и уменьшает его объем.
45
46
46
-
#### Limitations
47
-
If you are not targeting ES6 or above, the generated code assumes the property `length`exists on the object and that the object can be indexed via numbers e.g. `obj[2]`. So it is only supported on `string` and `array` for these legacy JS engines.
47
+
#### Ограничения
48
+
Для версий JS до ES6, сгенерированный код предполагает, что свойство `length`существует на объекте и этот объект может быть проиндексирован по номерам, например `obj[2]`. Это поддерживается только для строк и массивов для устаревших движков JS.
48
49
49
-
If TypeScript can see that you are not using an array or a string it will give you a clear error *"is not an array type or a string type"*;
50
+
Если вы используете `for...of` не на массиве или строке, TypeScript сообщит об это ошибкой *"is not an array type or a string type"*.
50
51
```ts
51
52
let articleParagraphs =document.querySelectorAll("article > p");
52
-
//Error: Nodelist is not an array type or a string type
53
+
//Ошибка: Nodelist is not an array type or a string type
53
54
for (let paragraph ofarticleParagraphs) {
54
55
paragraph.classList.add("read");
55
56
}
56
57
```
57
58
58
-
Use`for...of`only for stuff that *you know* to be an array or a string. Note that this limitation might be removed in a future version of TypeScript.
59
+
Используйте`for...of`только для случаев, когда *вы уверены*, что применяете это к строке или массиву. Помните, что это ограничение может быть удалено на следующих версиях TypeScript.
59
60
60
-
#### Summary
61
-
You would be surprised at how many times you will be iterating over the elements of an array. The next time you find yourself doing that, give `for...of` a go. You might just make the next person who reviews your code happy.
61
+
#### Заключение
62
+
Вы можете удивиться, как часто вы итерируете элементы массива. В следующий раз, когда будете это делать, попробуйте использовать `for...of`. Вы можете просто порадовать следующего человека, который просматривает ваш код.
0 commit comments