Why do the document.write() and alert() methds render JavaScript objects differently? -
what difference between document.write() method , window.alert() when printing arrays , objects?
the different behaviors shown in code sample:
var arr = new array("maizere","pathak"); document.write(arr); // output: maizere,pathak alert(arr); // output: maizere,pathak why both printing values? shouldn't alert() print object object?
with dom object, prints [object html collection] , here printing values.
objects in javascript have tostring method. method called whenever object used in way text expected. instance, following outputs [object object]:
alert({}); arrays have own version of tostring method altogether different. rather showing type, show contents, joined commas. can replace arrays tostring method if like:
var names = ['jonathan', 'sampson']; names.tostring = function () { return this.length; }; alert(names); // outputs 2 you can use else's tostring implementation if like:
document.tostring.call(names); // [object array] for additional information, see tostring on msdn.
Comments
Post a Comment