在“for"循环中使用变量 [英] Use a variable in a 'for' loop

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

问题描述

我有以下代码:

@echo off设置 ITER=0对于 (%*) 中的 %%i 做 (设置 ITER+=1回声%ITER%)

输出是(对于三个参数):

<预><代码>000

预期输出:

123

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

解决方案

在执行语句/块之前使用百分比扩展变量.
因此,在您的情况下,在执行 echo %ITER% 之前将完整块扩展为常量 echo 0.
变量 ITER 本身在循环中正确更新.

为了避免这种情况,您可以使用延迟扩展,这类似于百分比扩展,但只是在执行的那一刻

@echo offsetlocal EnableDelayedExpansion设置 ITER=0对于 (%*) 中的 %%i 做 (SET/a ITER+=1回声!ITER!)

I have following code:

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

The output is (for three arguments):

0
0
0

Expected output:

1
2
3

Why can't I access the updated variable in the for loop?

解决方案

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!
)

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

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