问题
<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