Skip to content

Commit 9e9ec9f

Browse files
committed
array/general
1 parent c0c814d commit 9e9ec9f

File tree

1 file changed

+14
-32
lines changed

1 file changed

+14
-32
lines changed

doc/ru/array/general.md

Lines changed: 14 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,29 @@
1-
## Array Iteration and Properties
1+
##  Итерации по массивам и свойства
22

3-
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` в массивах.
64

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). И при том, что ассоциативные массивы **сохраняют** заданный порядок, объекты **не** делают этого.
106
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`.
158

16-
### Iteration
9+
### Итерирование
1710

18-
In order to achieve the best performance when iterating over arrays, it is best
19-
to use the classic `for` loop.
11+
Для достижения лучшей производительности при итерации по массивам, лучше всего использовать обычный цикл `for`.
2012

2113
var list = [1, 2, 3, 4, 5, ...... 100000000];
2214
for(var i = 0, l = list.length; i < l; i++) {
2315
console.log(list[i]);
2416
}
2517

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`.
2819

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 **могут** применять оптимизацию, нет способа узнать, будет оптимизирован код на новом движке или нет.
3321

34-
In fact, leaving out the caching may result in the loop being only **half as
35-
fast** as with the cached length.
22+
Фактически, отсутствие кэширования может привести к выполнению цикла в **два раза медленнее**, чем при кэшировании длины
3623

37-
### The `length` property
24+
### Свойство `length`
3825

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` просто возвращает количество элементов содежащихся в массиве, *сеттер* можно использовать для **обрезания** массива.
4227

4328
var foo = [1, 2, 3, 4, 5, 6];
4429
foo.length = 3;
@@ -47,12 +32,9 @@ elements that are contained in the array, the *setter* can be used to
4732
foo.length = 6;
4833
foo; // [1, 2, 3]
4934

50-
Assigning a smaller length does truncate the array, but increasing the length
51-
does not have any effect on the array.
35+
Присвоение свойству `length` меньшей величины урезает массив, однако присвоение большего значения не влечёт никакого эффекта.
5236

53-
### In conclusion
37+
### Заключение
5438

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` с массивами является признаком плохого кода, обладающего предпосылками к ошибкам и может привести к низкой скорости его выполнения.
5840

0 commit comments

Comments
 (0)