如何使用javascript在for循环中存储变量值

时间:2022-04-04 14:01:23

I am using for loop in javascript and store value in multiple variables.

我在javascript中使用for循环并在多个变量中存储值。

 var    friend_id1 = '';
 var    friend_id2 = '';
 var    friend_id3 = '';

 FB.api('/me/friends', function(response) {
    if(response.data) {
        obj = response.data
        obj = shuffle(obj);
        a = 3;
        for(x = 1; x <= obj.length; x++){
            friend_id[x] = obj[x].id;
        if(x >= a) break;
        }
    } else {
        alert("Error!");
    }
});

if i replace friend_id[x] to friend_id1 i will get user id. But i want store values in multiple variables.

如果我将friend_id [x]替换为friend_id1,我将获得用户ID。但我希望商店值在多个变量中。

1 个解决方案

#1


0  

You're trying to save the values to an array:

您正在尝试将值保存到数组:

friend_id[x] = obj[x].id;

But you didn't declare an array, you have no array variable called friend_id. Instead, you have multiple variables with numbered names.

但是你没有声明一个数组,你没有名为friend_id的数组变量。相反,您有多个带编号名称的变量。

Just declare the array as you want to use it:

只需声明数组即可使用它:

var friend_id = [];

Or, more aptly named:

或者,更恰当地命名:

var friend_ids = [];

And more properly used:

并且使用得更恰当:

friend_ids.push(obj[x].id);

#1


0  

You're trying to save the values to an array:

您正在尝试将值保存到数组:

friend_id[x] = obj[x].id;

But you didn't declare an array, you have no array variable called friend_id. Instead, you have multiple variables with numbered names.

但是你没有声明一个数组,你没有名为friend_id的数组变量。相反,您有多个带编号名称的变量。

Just declare the array as you want to use it:

只需声明数组即可使用它:

var friend_id = [];

Or, more aptly named:

或者,更恰当地命名:

var friend_ids = [];

And more properly used:

并且使用得更恰当:

friend_ids.push(obj[x].id);