23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 4 ■ CONTROLLING FLOW<br />

falsy element from looseLeafTea by way of the predefined splice()method, which we will cover in more<br />

detail in Chapter 5, that just removes the element from the array and then brings the subsequent<br />

elements forward to fill the gap. Second, we will insert a continue statement to abort the iteration. This<br />

statement will halt the current iteration of the loop and jump back to the start of the while loop with a<br />

new iteration. Note that this means we will skip the i ++ line of code, so the counter will not be<br />

incremented. This is exactly what we want to happen because, when we removed the falsy element,<br />

JavaScript brought all the remaining elements forward to fill the gap, so there is a new element now<br />

occupying the position of the old falsy element. For that reason, we want to loop over the same index in<br />

the array twice to make sure we cover all the elements. Finally, let’s increment i within an else clause<br />

just to make things read better.<br />

So, modify the previous sample like so, and click Run in Firebug:<br />

var looseLeafTea = [<br />

"Ghillidary",<br />

"",<br />

"Kenilworth",<br />

"Milima",<br />

,<br />

"Keemun",<br />

"Boisahabi",<br />

"Manohari",<br />

"Borpatra",<br />

"Lukwah",<br />

"Khongea"<br />

];<br />

var mood = "glum";<br />

var i = 0;<br />

while (i < looseLeafTea.length) {<br />

if (looseLeafTea[i] === "Borpatra") {<br />

mood = "cheery";<br />

break;<br />

} else if (! looseLeafTea[i]) {<br />

looseLeafTea.splice(i, 1);<br />

continue;<br />

} else {<br />

i ++;<br />

}<br />

}<br />

"I feel " + mood + "!";<br />

// "I feel cheery!"<br />

Before moving on, let’s check to make sure JavaScript did weed out the "" and undefined values<br />

from looseLeafTea. So, click Clear, and then query looseLeafTea like so, verifying your work with Figure<br />

4–9:<br />

looseLeafTea;<br />

// ["Ghillidary", "Kenilworth", "Milima", "Keemun", "Boisahabi", "Manohari",<br />

// "Borpatra", "Lukwah", "Khongea"]<br />

So there it is. JavaScript deleted the "" and undefined elements just like we wanted.<br />

119

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!