0
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?

1
  • "without change the script within the function"... that's not going to be possible. Why can you not change the function? Commented Jul 15, 2012 at 16:25

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

There's another way to change it?
Yes, of course. If you change the implementation of this function you could add whatever values you want to the array. The array could also be passed as argument. This way the caller of the function could provide his own array of values.
1

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.

2 Comments

Why do you consider writeln worse than eval?
You can get around bad code written in 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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.