For..of 循环混乱

问题描述 投票:0回答:1

所以我一直只用 (let i = 0; i < arr.length; i++) set up until now. This is visually something you can break down and understand so its been logical for me. Now I'm being taught the for..of loop and it's not as easy to directly see whats going on. I understand its just a simpler way to write it in relation to arrays - but I'm wondering if they have designed it to operate as a function with the keywords 'for' 'const' and 'of' or if someone might be able to help me understand how this code is actually operating?

我试图向某人提出这个问题,但从他们的回答来看,这可能只是你在没有真正看到其本身运作逻辑的情况下所做的事情之一。据我所知,它的运行更像是一个带参数的函数?

const clay = [ "Clay", "Clay", "Clay", "Clay" ]
const toFireInKiln = []

for (const i of clay) {
   const mug = `${i} coffee mug`
   toFireInKiln.push(mug)
}



console.log(toFireInKiln)

我可以使用它,因为它应该被使用,但我不理解它运行时的功能。

arrays for-loop logic increment semantics
1个回答
0
投票

我不知道这个 C# 示例是否有帮助,但这里有两个版本的代码 - 一个使用

foreach
,另一个使用使其工作的底层方法调用。

IEnumerable<string> letters = new[] { "A", "B", "C" };

foreach (string letter in letters)
{
    Console.WriteLine(letter);
}

using (var e = letters.GetEnumerator())
{
    while (e.MoveNext())
    {
        Console.WriteLine(e.Current);
    }
}

这两个代码块生成的 IL(字节码)几乎相同。

© www.soinside.com 2019 - 2024. All rights reserved.