简体   繁体   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);

This returns " myNameundefiend " that is the value+undefined why is that happening ? 这将返回“ myNameundefiend”,即值+未定义,为什么会发生?

You're not returning a value from your test function, making the testcheck variable undefined . 您没有从test函数返回值, testcheck使testcheck变量为undefined

The test() call first writes the name to the document, then document.write(testcheck); test()调用首先将名称写入文档,然后document.write(testcheck); adds undefined behind that. 在其后添加undefined

You'll need to return name from the function: 您需要从函数return name

function test() {
    document.write(name);
    return name;
}

There's no need to document.write twice. 无需document.write两次。 Either only keep it in the function, or remove it from the function and use document.write(testcheck); 要么只将其保留在函数中,要么将其从函数中删除,然后使用document.write(testcheck); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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