formations/javascript/base/tableaux-2.md

49 lines
819 B
Markdown
Raw Normal View History

2015-03-25 17:27:03 +01:00
# .cadoles-slide-title[Tableaux (2/2)]
.cadoles-clearfix[
**Méthodes de parcours et transformations**
]
```js
var arr = [1, 2, 3];
// Traverser le tableau
arr.forEach(function(item, index) {
console.log('Item:', item, 'Index:', index);
});
// Transformer un tableau
var square = arr.map(function(item, index) {
return item*item;
}); // -> [1, 4, 9]
// Réduire un tableau
var sum = arr.reduce(function(memo, item, index) {
return memo+item;
}, 0); // -> 6
```
**Exercice**
```js
var arr = [15, 20, 15, 16, -1, 4];
var max = arr.??(function(??) {
??
}, ??);
console.log(max); // -> 20
```
???
Solution Exo
```js
var arr = [15, 20, 15, 16, -1, 4];
var max = arr.reduce(function(memo, item, index) {
if(!memo) {
memo = item;
} else if(item >= memo) {
memo = item;
}
return memo;
});
```