繁体   English   中英

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

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

我有两个 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"

映射 function 将在迭代时返回一个数组。 解决此问题的一种方法是比较两个 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" 

您不能访问其范围之外的变量。 因此,请执行以下操作:

在 scope of.map() 之外声明myFollowersmyFollowings并用一些值初始化它们。

然后,您可以从 .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