如何在同一个 for 循环中运行三个单独的数组? [英] How can I run through three separate arrays in the same for loop?

查看:24
本文介绍了如何在同一个 for 循环中运行三个单独的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试运行三个数组,我想在一个函数中使用所有三个数组中的值.这听起来可能令人困惑,但这是我所拥有的:

I have three arrays I am trying to run through and I want to use the values from all three arrays in one function. This might sound confusing but here is what I have:

    var Name = [Joe, Sarah, Chad]
    var Age = [18, 20, 22]
    var Gender = [Male, Female, Male]

    for name in Name {
        for age in Age {
            for gender in Gender {   
                makeUser(name, userAge: age, userGender: gender)
            }
        }
    } 

这会运行,但我得到的是:(makeUser 打印出 3 个值)

This runs but what I get is: (makeUser prints out the 3 values)

Joe, 18, Male
Joe, 20, Male
Joe, 22, Male

Joe, 18, Female
Joe, 20, Female
Joe, 22, Female ....

等等.

我想要的是

Joe, 18, Male
Sarah, 20, Female
Chad, 22, Male

这可能吗?任何帮助表示赞赏.

Is this possible? Any help is appreciated.

谢谢!

推荐答案

如果您总是确定数组的长度相等,那么您最好只循环遍历其中一个数组并使用它的索引来引用其他数组:

If you are always sure the arrays will be equal in length, then you are better to just loop through one of the arrays and use it's index to reference the others:

for (index, name) in enumerate(Name) {
    makeUser(name, userAge: Age[index], userGender: Gender[index])
}

但是,我建议将这些数据放入字典中,但我认为这只是示例数据来说明一点.:)

However, I would recommend getting this data into a dictionary, but I assume this is just sample data to illustrate a point. :)

这篇关于如何在同一个 for 循环中运行三个单独的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆