0

グローバル変数がaあり、関数内で使用して値を割り当てています。関数の外でこの変数を使用すると、undefined.

例えば。:

var a;
function my_func(){
  a=5;
}
console.log(a); //outputs undefined, how do I get the value 5 here

undefinedの代わりに取得するのはなぜ5ですか?


それは私の問題を解決しません。

var id;

function set_id(myid){
 id=myid;
}

function get_id(){
 return id;
}

$("#btn").click(function(){
 $.post("....", function(data){ //data reurns a JSON
  set_id(id); //success!!
 }
}

$("#show").click(function()[
 console.log(get_id()); //doesn't work, how do I get this workin.. Where am I going wrong
}
4

2 に答える 2

3

my_funcログの前に関数を呼び出す必要があります。

var a;
function my_func(){
  a=5;
}
my_func();      //<-- here
console.log(a);
于 2012-07-27T18:43:59.057 に答える
0
var a;

function my_function1() {
    return 5;
}

function my_function2() {
    a = 5;
}

/* Either of these options below will work to change the value of "a" to 5*/

// a = my_function1()
// my_function2()​​​
于 2012-07-27T19:08:18.710 に答える