【问题标题】:What is the term for the "current/temporary element" inside a For-loop?For循环中的“当前/临时元素”的术语是什么?
【发布时间】:2021-08-05 04:17:59
【问题描述】:

我想知道您在 for 循环中访问的“临时变量”的名称。它不是真正特定于语言的,但这是我在 Swift 中的代码:

let array = [1, 2, 3]
for number in array {
    print(number) /// what is this?
}

什么是number,每次迭代都不同的“临时变量”,称为?

这是我试图描述它的尝试。

  • 当前迭代的元素
  • 当前元素

那么,如果我在数组的索引上循环呢?在这种情况下我如何引用number

let list = [1, 2, 3]
for i in 0..<list.count {
    let number = list[i] /// what is this?
    print(number)
}

我的尝试:

  • list 数组在当前迭代索引处的元素
  • list 数组在循环当前迭代索引处的元素

【问题讨论】:

  • @aheze 您是否要迭代数组的索引和元素?
  • 代码一和二都将打印数组的element(value)。但是第一个您直接调用数组的值,第二个将通过数组索引调用值。
  • 在这两种情况下,number 都是存在于for 循环范围内的局部变量,因此它与任何其他变量没有什么不同,因为它存在于它被声明的范围内。
  • 又称索引变量

标签: arrays swift loops


【解决方案1】:

让我们举一个例子。

let array = [1, 2, 3]
for number in array {
    print(number)
}

对于上述情况,循环将打印数组的每个数字(元素/对象)(不是元素的索引)。

这意味着如果数组是 [a,b,c,d], 它会打印 abcd

对于第二种情况,您在数组范围内迭代循环,然后根据索引获取元素

let list = [1, 2, 3]
for i in 0..<list.count {
    let number = list[i] /// what is this?
    print(number)
}

上面的例子,i 引用了一个数组值的索引,并且 let number = list[i] 代码将在 i 索引处为您提供一个元素。

最后,如果您希望两个索引都包含在一个循环中的元素。你可以使用.enumerated()

这是一个例子

let array = [1, 2, 3]
for (index, number) in array.enumerated() {
    print("Array object/ Element Index :- ", index)
    print("Array object/ Element :- ", number)
}

【讨论】:

  • i 索引处的元素”我想这已经接近了,谢谢!
  • 索引处的元素指的是数组中的一个值,而不是它所分配给的变量。
  • 是的,我的意思是这个。只是句子单词错误。谢谢
  • @aheze 使用枚举时要小心。它返回偏移量而不是索引。如果您将它与集合的一部分一起使用,它可能会使您的应用程序崩溃。您应该始终使用它的索引。 stackoverflow.com/a/54877538/2303865
  • @LeoDabus 谢谢,明白了!其实我只是想找出迭代器事物的学术术语(它似乎被称为“索引变量”)。 RajaKishan 刚刚给出了一个(非常感谢的)扩展答案。
猜你喜欢
  • 2016-04-08
  • 1970-01-01
  • 2016-01-14
  • 2022-11-23
  • 1970-01-01
  • 2021-10-30
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多