javascript - How to set a global variable in function - Stack Overflow

I read through similar topics, but couldn't find an answer.Here is the code:foo_arr = ["a&quo

I read through similar topics, but couldn't find an answer.

Here is the code:

foo_arr = ["a", "b", "c"]
bar_arr = ["x", "y"]

test(bar_arr);
document.write(bar);

function test(arr_name) {
    bar = Math.random()*arr_name.length;

    if (bar < 1) {test(arr_name)}
}

As you can see I pass the array name to the function, but what if I need to pass a variable too? For instance

test(bar, bar_arr);

function test(var_name, arr_name) {
    var_name = Math.random()*arr_name.length;

It won't work. Why and how to do this?

I read through similar topics, but couldn't find an answer.

Here is the code:

foo_arr = ["a", "b", "c"]
bar_arr = ["x", "y"]

test(bar_arr);
document.write(bar);

function test(arr_name) {
    bar = Math.random()*arr_name.length;

    if (bar < 1) {test(arr_name)}
}

As you can see I pass the array name to the function, but what if I need to pass a variable too? For instance

test(bar, bar_arr);

function test(var_name, arr_name) {
    var_name = Math.random()*arr_name.length;

It won't work. Why and how to do this?

Share Improve this question asked Mar 2, 2011 at 16:28 Daniel J FDaniel J F 1,0642 gold badges16 silver badges31 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You cannot pass (references to) variables in JavaScript, only their values. Even with bar_arr, you are only passing the "value" of the array, which is an object -- you can modify the object's properties this way, but you can't change bar_arr itself.

To really "pass" a variable, take the above trick one step back and use the object which contains the variables as properties. In this case, that is the window object of which all global variables are a property:

function test(var_name) {
  window[var_name] = 'foo';
}

test('bar'); // note that the property name is a string, not a variable
alert(bar); // now the global 'bar' is set

If you want to set the value of only one global variable, you can return the wanted value from your fonction :

function test(arr_name) {
    return Math.random()*arr_name.length;
}

bar = test(bar_arr);

I'm really not sure that's what you want to do, but I'm glad if I was able to help.

If var_name is a global variable, you can still access it inside function test. Example:

var_name; // global
function test(arr_name) {
    var_name = Math.random()*arr_name.length;  // still accessible here

    if (bar < 1) {test(arr_name)}
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745381952a4625269.html

相关推荐

  • javascript - How to set a global variable in function - Stack Overflow

    I read through similar topics, but couldn't find an answer.Here is the code:foo_arr = ["a&quo

    12小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信