Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

ARRAY FUNCTIONS

PROF. DAVID ROSSITER

1/8

AFTER THIS PRESENTATION


You'll learn some more advanced array functions

2/8

WE'LL LOOK AT
forEach()
map()

3/8

FOREACH()
You can go through every element using loop (for / while)
varpets=["Dog","Cat","Hamster"]
for(vari=0i<pets.lengthi++){
alert(pets[i])
}

You can also use array.forEach(function):


varpets=["Dog","Cat","Rabbit"]
pets.forEach(alert)
//Thisshows3separatealerts

4/8

MORE ON FOREACH()
You can think of forEach() in this way:
functionforEach(theArray,fn){
for(vari=0i<theArray.lengthi++){
fn(theArray[i],i,theArray)
}
}

So, your function should look like this,


if you need all of the 3 things:
functionyourFunction(element,index,array){}

5/8

<!doctypehtml>
<html>
<body>
<script>
varnumbers=[1,2,3,4,5]
numbers.forEach(function(elem,idx,arr){
arr[idx]=elem*elem
})
alert(numbers)//Thisshows[1,4,9,16,25]
</script>
</body>
</html>

6/8

MAP()
map(function) stores the result of each execution
of function into an array it returns.
You can think of map() in this way:
functionmap(theArray,fn){
varresults=[]
for(vari=0i<theArray.lengthi++){
results.push(fn(theArray[i],i,theArray))
}
returnresults
}

7/8

<!doctypehtml>
<html>
<body>
<script>
varsquare=function(el){returnel*el}
varnumbers=[1,2,3,4,5]
varresults=numbers.map(square)
alert(results)//Thisshows[1,4,9,16,25]
</script>
</body>
</html>

8/8

You might also like