update global variable from a function in the javascript

我与影子孤独终老i 提交于 2021-02-10 14:01:39

问题


Here is the situation:

I have one function which has local variable. I would like to assign that value to global variable and us it's value in another function.

Here is the code:

global_var = "abc";

function loadpages()
{
    local_var = "xyz";
    global_var= local_var;
}

function show_global_var_value()
{
    alert(global_var);
}

I'm calling show_global_var_value() function in the HTML page but it shows the value = "xyz" not "abc"

What am I doing wrong?


回答1:


What you need to do apart from declaring local variables with var statement as other pointed out before, is the let statement introduced in JS 1.7

var global_var = "abc";

function loadpages()
{
    var local_var = "xyz";
    let global_var= local_var;
    console.log(global_var); // "xyz"
}

function show_global_var_value()
{
    console.log(global_var); // "abc"
}

Note: to use JS 1.7 at the moment (2014-01) you must declare the version in the script tag:

<script type="application/javascript;version=1.7"></script>

However let is now part of ECMAScript Harmony standard, thus expected to be fully available in the near future.



来源:https://stackoverflow.com/questions/2819440/update-global-variable-from-a-function-in-the-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!