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
Although arrays in JavaScript are objects, there are no good reasons to use
4
-
the [`for in loop`](#object.forinloop) in for iteration on them. In fact there
5
-
are a number of good reasons **against** the use of `for in` on arrays.
3
+
Не смотря на то, что массивы в JavaScript являются объектами, нет достаточных оснований для использования [цикла `for in`](#object.forinloop) для итерации по элементами. Фактически, существует несколько весомых причин **против** использования `for in` в массивах.
6
4
7
-
> **Note:** JavaScript arrays are **not***associative arrays*. JavaScript only
8
-
> has [objects](#object.general) for mapping keys to values. And while associative
9
-
> arrays **preserve** order, objects **do not**.
5
+
> **Замечание:** Массивы в JavaScript **не** являются *ассоциативными массивами*. Для связывания ключей и значений в JavaScript есть только [объекты](#object.general). И при том, что ассоциативные массивы **сохраняют** заданный порядок, объекты **не** делают этого.
10
6
11
-
Since the `for in` loop enumerates all the properties that are on the prototype
12
-
chain and the only way to exclude those properties is to use
13
-
[`hasOwnProperty`](#object.hasownproperty), it is already up to **twenty times**
14
-
slower than a normal `for` loop.
7
+
Во время выполнения `for in` циклически перебираются все свойства объекта, находящиеся в цепочке прототипов. Единственный способ исключить ненужные свойства — использовать [`hasOwnProperty`](#object.hasownproperty), а это **в 20 раз** медленнее обычного цикла `for`.
15
8
16
-
### Iteration
9
+
### Итерирование
17
10
18
-
In order to achieve the best performance when iterating over arrays, it is best
19
-
to use the classic `for` loop.
11
+
Для достижения лучшей производительности при итерации по массивам, лучше всего использовать обычный цикл `for`.
20
12
21
13
var list = [1, 2, 3, 4, 5, ...... 100000000];
22
14
for(var i = 0, l = list.length; i < l; i++) {
23
15
console.log(list[i]);
24
16
}
25
17
26
-
There is one extra catch in the above example, that is the caching of the
27
-
length of the array via `l = list.length`.
18
+
В примере выше есть один дополнительный приём, с помощью которого кэшируется величина длины массива: `l = list.length`.
28
19
29
-
Although the `length` property is defined on the array itself, there is still an
30
-
overhead for doing the lookup on each iteration of the loop. And while recent
31
-
JavaScript engines **may** apply optimization in this case, there is no way of
32
-
telling whether the code will run on one of these newer engines or not.
20
+
Не смотря на то, что свойство length определено в самом массиве, поиск этого свойства накладывает дополнительные расходы на каждой итерации цикла. Несмотря на то, что в этом случае новые движки JavaScript **могут** применять оптимизацию, нет способа узнать, будет оптимизирован код на новом движке или нет.
33
21
34
-
In fact, leaving out the caching may result in the loop being only **half as
35
-
fast** as with the cached length.
22
+
Фактически, отсутствие кэширования может привести к выполнению цикла в **два раза медленнее**, чем при кэшировании длины
36
23
37
-
### The`length` property
24
+
### Свойство`length`
38
25
39
-
While the *getter* of the `length` property simply returns the number of
40
-
elements that are contained in the array, the *setter* can be used to
41
-
**truncate** the array.
26
+
Несмотря на то, что *геттер* свойства `length` просто возвращает количество элементов содежащихся в массиве, *сеттер* можно использовать для **обрезания** массива.
42
27
43
28
var foo = [1, 2, 3, 4, 5, 6];
44
29
foo.length = 3;
@@ -47,12 +32,9 @@ elements that are contained in the array, the *setter* can be used to
47
32
foo.length = 6;
48
33
foo; // [1, 2, 3]
49
34
50
-
Assigning a smaller length does truncate the array, but increasing the length
51
-
does not have any effect on the array.
35
+
Присвоение свойству `length` меньшей величины урезает массив, однако присвоение большего значения не влечёт никакого эффекта.
52
36
53
-
### In conclusion
37
+
### Заключение
54
38
55
-
For the best performance it is recommended to always use the plain `for` loop
56
-
and cache the `length` property. The use of `for in` on an array is a sign of
57
-
badly written code that is prone to bugs and bad performance.
39
+
Для оптимального работы кода рекомендуется всегда использовать простой цикл `for` и кэшировать свойство `length`. Использование `for in` с массивами является признаком плохого кода, обладающего предпосылками к ошибкам и может привести к низкой скорости его выполнения.
0 commit comments