简体   繁体   English

如何访问在 map 之外声明的变量呢?

[英]how to access variables declared in map outside it?

I have two map functions and have assigned its data to variables, I want to compare them我有两个 map 函数并将其数据分配给变量,我想比较它们

!followerLoading && (
    followersData.map((e) => 
        {
            const myFollowers = e.requested_profile.Userlink
        }
    )
)

!followingLoading && (
followingData.map((e) => 
    {
        const myFollowings = e.requesting_profile.Userlink
    }
)
)

const btntext = myFollowers===myFollowings ? "Following" : "Follow"

The mapping function will return an array as it iterates over.映射 function 将在迭代时返回一个数组。 One way to tackle this problem is to compare the two arrays解决此问题的一种方法是比较两个 arrays

const myFollowers = !followerLoading && (
    followersData.map((e) => e.requested_profile.Userlink )
)

const myFollowings = !followingLoading && (
followingData.map((e) => e.requesting_profile.Userlink)
)

const btntext = arr1.some(r=> arr2.includes(r))  ? "Following" : "Follow" 

You cannot access variables outside of their scopes.您不能访问其范围之外的变量。 So do the following:因此,请执行以下操作:

Declare myFollowers and myFollowings outside the scope of.map() and initialize them with some values.在 scope of.map() 之外声明myFollowersmyFollowings并用一些值初始化它们。

Then you can assign values to those variables from the.map() methods.然后,您可以从 .map() 方法为这些变量赋值。

let myFollowers = null;
let myFollowing = null;

followerLoading && (
    followersData.map((e) => 
        {
            myFollowers = e.requested_profile.Userlink
        }
    )
)
// Same for the other one

const btntext = myFollowers===myFollowings ? "Following" : "Follow";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM