在for循环中声明两个变量 [英] Declaring two variables in a for loop

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

问题描述

是否可以在for循环的初始化部分声明两个变量?我想在字符串的每个字符上调用一个函数。

Is it possible to declare two variables in the initialization part of a for loop? I want to call a function on each character of a string.

for(var i = 0, c = aString.charAt(i); i < aString.length; i++){//problem here: not itterating
    alert("c: "+c)
    func1[typeOfChar(c)]++
}

问题是字符串在某种意义上没有被删除 c 始终是字符串的第一个字母。
顺便说一下,提醒仅用于解决问题。

The problem is the string isn't being itterated in the sense c is always the first letter of the string. The alert was just for trouble shooting purposes, by the way.

我很好奇,怎么来 c 在申报时不需要 var 关键字?

I'm curious, how come c doesn't need the var keyword when being declared?

更新:让它运转起来。我不会问,但我注意到编辑仍在进行中,我习惯不使用分号,因为它们是可选的。没有它们,如何编写for循环?我不添加它们,因为我认为它不那么简单,或者它们是否提高了可读性?

UPDATE: got it working. I wasn't going to ask but I notice edits are still being made, I'm used to not using the semi-colons as they are optional. How can a for loop be written without them? I don't add them because I see it as the less the simpler, or do they improve readability?

推荐答案

你会比如 c 要在每次迭代时更改,而不是在循环开始时声明它,请尝试

You'd like c to change at every iteration, not to declare it at the start of the loop, try

var i,c;
for(i = 0,c=aString.charAt(0); i < aString.length; ++i, c = aString.charAt(i)){
    alert("c: "+c)
    func1[typeOfChar(c)]++
}

为了它的价值我不认为它使代码非常易读,我会把它放在第一行。

For what it's worth I don't think it makes very readable code, I would put it in the first line.

这是一些信息您正在使用的逗号运算符

另请注意,javascript没有for循环的块作用域,所以你实际上是在声明 i c 当前范围的顶部(通常是当前函数的顶部,或全局范围的顶部)。

Also note that javascript has no block scoping for for loops, so you're actually declaring i and c at the top of the current scope (this is usually the top of the current function, or the top of the global scope).

这是一个小提琴:http://jsfiddle.net/maWua/

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

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