function animal(){
var species = new Array('Monkey', 'Dog', 'Cat');
for(i=0;i<species.length;i++)
{
document.writeln(species[i]);
}
}
How can I add another value to the species array without modifying the animal() function?
function animal(){
var species = new Array('Monkey', 'Dog', 'Cat');
for(i=0;i<species.length;i++)
{
document.writeln(species[i]);
}
}
How can I add another value to the species array without modifying the animal() function?
It's impossible to add values to the array without changing the code of this function for the simple reason that the species variable used there is a local variable declared within the scope of the function. So this variable is not visible to outside code. In addition to that the values of this array are hardcoded. So forget about it. Impossible without touching at the function implementation.
I'm not sure I fully understand your concerns, but javascript unlike some other languages can entirely overwrite a function.
So, assuming the above code, I could do:
window.animal = function(){
var species = new Array('Monkey', 'Dog', 'Cat', 'Mouse', 'Fish');
for(i=0;i<species.length;i++)
{
document.writeln(species[i]);
}
}
That said, I would avoid the use of document.writeln(), I consider that function worse than eval()...
Also, as Darin hinted, I would also not define data local to a function if at all possible.
eval(), but not so much with writeln(). I had a particular case in Joomla where it used writeln() to write html to the document. My template got the script through AJAX and when it got executed, I kept getting a blank page with the written HTML (since writeln() clears the page when called after the document loads).