在fo​​r循环使用一个变量 [英] Use a variable in a 'for' loop

查看:164
本文介绍了在fo​​r循环使用一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code:

@echo off
SET ITER=0
for %%i in (%*) do (
  SET ITER+=1
  ECHO %ITER%
)

的输出(用于三个参数):

The output is (for three arguments):

0
0
0

期望的输出:

1
2
3

为什么我不能访问更新的变量在循环?

推荐答案

与百分比变量扩展执行语句/块之前完成。结果
所以你的情况完全块的前扩大回声%ITER%执行,恒呼应0 。< BR>
变量ITER本身在循环正常进行更新。

Expansion of variables with percents is done before a statement/block is executed.
So in your case the complete block is expanded before the echo %ITER% is executed, to constant echo 0.
The variable ITER itself is updated in the loop properly.

要避免这种情况,你可以使用延迟扩展,这就像扩展%,但就在执行的时刻

To avoid this, you could use the delayed expansion, this works like percent expansion but just in the moment of execution

@echo off
setlocal EnableDelayedExpansion
SET ITER=0
for %%i in (%*) do (
  SET /a ITER+=1
  ECHO !ITER!
)

这篇关于在fo​​r循环使用一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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