我们可以在JavaScript函数中通过引用传递变量吗?

时间:2015-03-22 13:35:50

标签: javascript

我正在通过javascript函数计算给定点的行和列。
要实现这一点,我必须声明全局变量

var global_row;
var global_col;

这是功能正文

function calculate_city_row_col(cur_city_id)
{
    var r = 565;
    var c = 1;
    var max_city_id = 159895;
    do{
        if((r%2) == 0) c++;
        max_city_id -= r;
        r--;
    }
    while(cur_city_id <= max_city_id)

    //Saving Result in seperate row and column
    global_row = r + 1;                                 //Global Variable
    global_col = c + (cur_city_id - (max_city_id + 1)); //Global Variable
}

这是函数调用

var city_id = 1244;
calculate_city_row_col(city_id);
var city_row = global_row;
var city_col = global_col;

无论如何直接传递局部变量? (不使用全局变量)
像这样

calculate_city_row_col(cur_city_id, city_row_ref, city_col_ref);

2 个答案:

答案 0 :(得分:2)

只需返回一个对象:

function calculate_city_row_col(cur_city_id)
{
    var r = 565;
    var c = 1;
    var max_city_id = 159895;
    do{
        if((r%2) == 0) c++;
        max_city_id -= r;
        r--;
    }
    while(cur_city_id <= max_city_id)

    return {
        row: r + 1,
        col: c + (cur_city_id - (max_city_id + 1))
    };
}

var rowAndCol = calculate_city_row_col(1244);
var city_row = rowAndCol.row;
var city_col = rowAndCol.col;

答案 1 :(得分:1)

  

我们可以通过JavaScript函数

中的引用传递变量

没有。 JavaScript纯粹是按值传递(传递对象时传递的值是对象引用,但它仍然是值)。

您的选择是:

  1. 让函数返回一个对象(或数组)

    function calculate_city_row_col(cur_city_id)
    {
        var r = 565;
        var c = 1;
        var max_city_id = 159895;
        do{
            if((r%2) == 0) c++;
            max_city_id -= r;
            r--;
        }
        while(cur_city_id <= max_city_id)
    
        //Saving Result in seperate row and column
        return {
            row: r + 1,
            col: c + (cur_city_id - (max_city_id + 1))
        };
    }
    

    用法:

    var result = calculate_city_row_col(someCityId);
    console.log(result.row);
    console.log(result.col);
    
  2. 让函数接受对它更新的对象(或数组)的引用

    function calculate_city_row_col(cur_city_id, result)
    {
        var r = 565;
        var c = 1;
        var max_city_id = 159895;
        do{
            if((r%2) == 0) c++;
            max_city_id -= r;
            r--;
        }
        while(cur_city_id <= max_city_id)
    
        //Saving Result in seperate row and column
        result.row = r + 1;
        result.col = c + (cur_city_id - (max_city_id + 1));
    }
    

    用法:

    var result = {};
    calculate_city_row_col(someCityId);
    console.log(result.row);
    console.log(result.col);
    
  3. 除非在特定情况下选择#2,否则#1通常是最佳选择。例如,如果您在紧密循环中调用此函数数千次,则可能是重用单个对象(通过传入)而不是每次都创建新对象的理由。 / p>