Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit dfb699a

Browse files
committed
Merge pull request airbnb#33 from rma4ok/master
[arrays] direct/push/copy
2 parents 12f9c99 + b7250a8 commit dfb699a

File tree

1 file changed

+33
-5
lines changed

1 file changed

+33
-5
lines changed

README.md

+33-5
Original file line numberDiff line numberDiff line change
@@ -112,22 +112,50 @@
112112
var items = [];
113113
```
114114
115-
- For [performance reasons](http://jsperf.com/array-direct-assignment-vs-push/5) use direct assignment over Array#push
115+
- When you are managing array length use direct assignment over Array#push for [performance reasons](http://jsperf.com/array-direct-assignment-vs-push/5)
116116
117117
```javascript
118-
var len = items.length,
119-
itemsCopy = [],
118+
var hundredOdds = [],
120119
i;
121120
122121
// bad
123-
for (i = 0; i < len; i++) {
124-
itemsCopy.push(items[i])
122+
for (i = 0; i < 100; i++) {
123+
hundredOdds.push(i * 2 + 1);
124+
}
125+
126+
// good
127+
for (i = 0; i < 100; i++) {
128+
hundredOdds[i] = i * 2 + 1;
125129
}
130+
```
131+
132+
- If you don't know array length use Array#push for [performance reasons](http://jsperf.com/array-direct-assignment-vs-push/5)
133+
134+
```javascript
135+
var someStack = [],
136+
137+
138+
// bad
139+
someStack[someStack.length] = 'abracadabra';
126140
127141
// good
142+
someStack.push('abracadabra');
143+
```
144+
145+
- When you need to copy an array use Array() constructor [performance](http://jsperf.com/converting-arguments-to-an-array/7)
146+
147+
```javascript
148+
var len = items.length,
149+
itemsCopy = [],
150+
i;
151+
152+
// bad
128153
for (i = 0; i < len; i++) {
129154
itemsCopy[i] = items[i];
130155
}
156+
157+
// good
158+
itemsCopy = Array.apply(null, items);
131159
```
132160

133161
**[[⬆]](#TOC)**

0 commit comments

Comments
 (0)