为什么在 PowerShell 中: for ($i=0; -le $total-1; $i++) 而不是 for ($i=0; -lt $total; $i++) ;)
我正在 powershellpro.com 上查看一些代码示例,不明白为什么他编写了通过以下方式循环遍历数组的示例代码:
...增量从零开始,然后增加一,直到小于或等于数组的长度减一...
for ($i=0; $i -le $total-1; $i++)
...而不是让增量从零开始然后增加一直到小于数组的长度...
for ($i=0; $i -lt $total; $i++)
我错过了什么吗?它们在功能上是等效的,并且都会循环遍历数组中的每个项目。我个人认为第二个版本更干净。是否有最佳实践或建议您应该使用第一个实践?
I'm looking at some code examples on powershellpro.com and don't understand why he wrote sample code that loops through an array by:
...having an increment start at zero then increase by one until it is less than or equal to the length of an array minus one...
for ($i=0; $i -le $total-1; $i++)
...instead of having the increment start at zero then increase by one until it is less than the length of the array...
for ($i=0; $i -lt $total; $i++)
Am I missing something? They are functionally equivalent and will both loop through each item in the array. Personally I think the second version is cleaner. Is there a best practice or something that says you should use the first one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
>>>我错过了什么吗?
否
>>是否有最佳实践或建议您应该使用第一个实践?
powershell 中“for”循环的用法与任何其他语言中的用法相同。只是取决于程序员的态度,他使用哪种风格。
>> Am I missing something?
No
>> Is there a best practice or something that says you should use the first one?
usage of 'for' cycle in powershell is the same like in any other language. just depends on attitude of the programmer which style he uses.
两者在功能上是等效的,但是代码越简洁,对于某些人来说就越容易阅读。另外,我认为原始发帖者的问题存在语法问题。 (如果我错了,请纠正我。)我提到这一点并不是为了批评,而是为了防止新手阅读本文并感到困惑。许多人可能认为这是相关代码片段的最佳版本:
请注意条件段中 -lt 之前的 $i。
Both are functionally equivalent, but the more concise the code, the easier it is to read for some people. Also, I think there's a syntax problem with the original poster's question. (Correct me if I'm wrong.) I mention this not as a critique, but only for in the event that a novice reads this and is confused. Many may consider this the best version of the code snippet in question:
Note the $i in the condition segment before -lt.
绝对没有区别。这只是品味问题。第一个片段将当
$i=$total-1
时停止循环。第二个之前$i=$total
。完全一样。恕我直言
There is absolutely no difference. it's just matter of taste. The first fragment will stop the loop when is
$i=$total-1
. The second before$i=$total
. it's exactly the same.IMHO