练涛

JavaScript、Java、C#关于for循环的比较

如下代码:

//JavaScript

<script>
window.onload=function(){
    var a=new Array('1','2','3','4','5');
    var i=0;
    for(i in a){    
        //这里不能写document.write(i);
        document.write(a[i]+"&nbsp;");
        };
    document.write("<br>下面是Array.forEach<br>");
        //不兼容ie
    a.forEach(function(a){
        document.write(a+"&nbsp;");
        });
}
</script>

结果:
jsFor

//C#

static void Main(string[] args)
        {
            int[] a={1,2,3,4,5};
            foreach(int i in a){    
                Console.Write(i+"  ");
                };
            Console.WriteLine();
        }

结果:
C#For

//Java

public static void main(String[] args) {
        // TODO Auto-generated method stub
        int a[]={1,2,3,4,5};
        for(int i : a)
        {   
          System.out.print(i+"  ");
            };
          System.out.println();

    }

结果:
JavaFor

同为for in 循环,js、C#、java还是有一些区别的。
其中,js的i并不能代替a[i],java的写法是 for : 。

posted @ 2017-03-20 14:11  练涛  阅读(138)  评论(0编辑  收藏  举报