why there is undefined when i run this

安稳与你 提交于 2021-01-29 17:02:10

问题


<html>
<head>
<title>js_trial</title>

<script language="javascript">
now = new Date();

document.write("today is: "+now+"<br/>");


function print (number){
if(number >= 4);

return document.write("the number "+number);
}

var num = 4;
var doub = print(num);

document.write(doub);
</script>
</head>
<body>





</html>

output: today is: Wed Feb 15 2012 23:31:19 GMT+0800 (Taipei Standard Time) the number 4undefined

why there is undefined after 4?


回答1:


The return value of document.write is always undefined.

You document.write the return value of print which has return document.write(...).




回答2:


Your if statement is not working:

now = new Date();

document.write("today is: "+now+"<br/>");

function print (number){
    if(number >= 4) {   
        document.write("the number "+number);
    }
}

var num = 4;
print(num);

And there is no response from document.write. Therefor 'undefined'.




回答3:


What you are doing when you call document.write(doub); is essentially doucment.write(document.write("the number "+number));.

undefined is the return value of the inner document.write call, which the outer document.write call is telling you has no value.




回答4:


the function document.write always returns undefined! What you do is: write "the number 4" to you document (document.write("the number "+number);) and store the return value of your write function (undefined) to the variable doub After that, you then write doub to your document as well which results in the appended "undefined".

what you would want to write instead of you code, is:

function print (number){
   if(number >= 4){
      return ("the number "+number);
   }
}

var num = 4;
var doub = print(num);
document.write(doub);

your function print now returns a string "the number 4" which is stored in doub and finally written to the document.

OR

function print (number){
   if(number >= 4){
      document.write("the number "+number);
   }
}

var num = 4;
print(num);

You call the function print, which writes "the number 4" to the document directly.

EDIT:

<script language="..."> is outdated, use <script type="text/javascript"> instead!

Your if condition does not work, use

  if (condition) {
     //your code here
  }


来源:https://stackoverflow.com/questions/9296284/why-there-is-undefined-when-i-run-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!