返回语句不工作,使用document.write

Return statement not working, with document.write

本文关键字:使用 document write 工作 语句 返回      更新时间:2023-09-26

为什么document.write(added);不能工作?

function first(){
    var now = new Date();
    var first=Math.round(now.getMilliseconds()/20);
    var second=Math.round(now.getMilliseconds()/30);
    var added=first+second;
    return added;
}
first();
document.write(added);

Javascript有函数作用域,这意味着在函数中声明的任何变量都不能在该函数之外访问。return added返回添加的,而不是变量added本身。如果要使用该值,则需要将其放在函数外部声明的变量中:

function first(){
    var now = new Date();
    var first=Math.round(now.getMilliseconds()/20);
    var second=Math.round(now.getMilliseconds()/30);
    var added=first+second;
    return added;
}
var firstResult = first();
document.write(firstResult);

更高级,但相关的:Javascript变量作用域的类型

因为added不是全局变量,因此当您调用document.write时,它超出了作用域。

您需要将返回值保存在调用document的同一作用域中的变量中。Write,即本例中的全局作用域。正确的代码应该是:

function first(){
var now = new Date();
var first=Math.round(now.getMilliseconds()/20);
var second=Math.round(now.getMilliseconds()/30);
var added=first+second;
return added;
}
var returnValue = first(); // store returned 'added' in returnValue
document.write(returnValue);

由于scope issue已经被指向,我将添加另一种方式来打印结果

document.write(first());