var name = "myName";
function test() {
document.write(name);
}
var testcheck= test();
document.write(testcheck);
这将返回“myNameundefiend ”,即值+未定义 为什么会发生这种情况?
最佳答案
您没有从 test
函数返回值,从而使 testcheck
变量未定义
。
test()
调用首先将名称写入文档,然后 document.write(testcheck);
在其后面添加 undefined
。
您需要从函数中返回
name
:
function test() {
document.write(name);
return name;
}
无需 document.write
两次。要么只将其保留在函数中,要么将其从函数中删除并使用 document.write(testcheck);
。
关于Javascript 使用在函数外部声明的变量返回值 + undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29414422/