[英]Javascript using a Variable declared outside the function returns the value + undefined along with it
var name = "myName";
function test() {
document.write(name);
}
var testcheck= test();
document.write(testcheck);
这将返回“ myNameundefiend”,即值+未定义,为什么会发生?
您没有从test
函数返回值, testcheck
使testcheck
变量为undefined
。
test()
调用首先将名称写入文档,然后document.write(testcheck);
在其后添加undefined
。
您需要从函数return
name
:
function test() {
document.write(name);
return name;
}
无需document.write
两次。 要么只将其保留在函数中,要么将其从函数中删除,然后使用document.write(testcheck);
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.