Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  151] [ 4]  / answers: 1 / hits: 68844  / 11 Years ago, sat, march 23, 2013, 12:00:00

I wrote the following JavaScript functions :



<script type=text/javascript>
function showVariable(val){
if(typeof(val)!=null && typeof(val)!=false &&typeof(val)!=NaN && typeof(val)!=undefined)
return typeof(val);
else
return val;
}
function print(){
var val = {1, 2, 3};
var res = showVariable(val);
alert(res);
}
</script>


Currently, I can see the result using alert, but I want to know if there is another method to print showVariable's result in my html document.


More From » function

 Answers
7

Others have pointed out how to add text to an existing HTML element. A couple other options are described below.



Error log



For debugging, an alternative to alert() that's less intrusive is to add the text to the error log. For instance, in Firefox with the Firebug extension:



if (console.log) console.log(res);


Document.write



Another option that probably won't apply to this particular question, but which is sometimes helpful, is to use document.write. Be careful not to use it after the page has loaded, however, or it will overwrite the page.



For example, the following:



<p>one</p>
<script type=text/javascript>document.write('<p>two</p>');</script>
<p>three</p>
<script type=text/javascript>document.write('<p>four</p>');</script>


Will be displayed in the browser as if the static HTML source code were:



<p>one</p>
<p>two</p>
<p>three</p>
<p>four</p>





typeof



On a side note, the typeof operator returns one of the following string values:



    'undefined'
'null' // For browsers that support ECMAScript 6+
'boolean'
'number'
'string'
'function'
'object'


The initial if statement could be refactored as follows:



Instead of this               Use this                     Or this
------------------- ----------------- ------------
typeof(val) != null val !== null
typeof(val) != false val !== false
typeof(val) != NaN typeof val == 'number' !isNaN(val)
typeof(val) != undefined typeof val != 'undefined'


Not sure if you need all of those tests though. It depends on what you're trying to do.


[#79404] Thursday, March 21, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
peytont

Total Points: 215
Total Questions: 110
Total Answers: 111

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
;