繁体   English   中英

使用在函数外部声明的变量的Javascript会返回值+未定义

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM