gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:19:16 25 4
gpt4 key购买 nike

我正在通过 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);

最佳答案

只返回一个对象:

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;

关于javascript - 我们可以在 JavaScript 函数中通过引用传递变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29195017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com