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 6 ■ FUNCTIONS AND ARRAYS<br />

250<br />

"16": [1994, 53, 61],<br />

"17": [1993, 75, 87],<br />

"length": 18,<br />

"callee": argumentsToArray<br />

};<br />

Inserting or Deleting Elements from an Array<br />

Now then, say the elements for the 2000–2002 seasons are invalid inasmuch as the wins and losses are<br />

reversed, and 2002 is in there twice. To delete those four invalid elements and insert new ones in their<br />

place, we can invoke splice() on pirates.<br />

• The first parameter is the index of the first element to delete, so 8 for the 2002<br />

season.<br />

• The second parameter is the number of elements to delete, which would be 4.<br />

• From there, any additional parameters are elements to splice into the array. Note<br />

that it’s OK to add more or fewer elements than you deleted; JavaScript will keep<br />

the array indexes sequential behind the scenes.<br />

So if we add three elements in place of the four invalid ones, the indexes in pirates remain<br />

sequential, ordered 0 to 17 as Figure 6–39 displays.<br />

var pirates = [[2010, 57, 105],<br />

[2009, 62, 99],<br />

[2008, 67, 95],<br />

[2007, 68, 94],<br />

[2006, 67, 95],<br />

[2005, 67, 95],<br />

[2004, 72, 89],<br />

[2003, 75, 87],<br />

[2002, 89, 72],<br />

[2002, 89, 72],<br />

[2001, 100, 62],<br />

[2000, 93, 69],<br />

[1999, 78, 83],<br />

[1998, 69, 93],<br />

[1997, 79, 83],<br />

[1996, 73, 89],<br />

[1995, 58, 86],<br />

[1994, 53, 61],<br />

[1993, 75, 87]];<br />

pirates.splice(8, 4, [2002, 72, 89], [2001, 62, 100], [2000, 69, 93]);<br />

console.dir(pirates);

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

Saved successfully!

Ooh no, something went wrong!