Unity 3D游戏开发 - C#语法基础 | 数组之元素遍历

for 循环遍历数组

  • 数组遍历
    • 把数组元素依次取出来
  • 遍历取值
    int[] intArray = new int[]{11,22,33,44,55,66,77,88,99};
    for(int i = 0; i <= intArray.Length - 1; i++)    //intArray.Length:取得当前数组长度.
    {
      Console.WriteLine(intArray[i]);
    } 
    Console.ReadKey();
  • 遍历赋值
                string[] str = new string[5];
                for (int i = 0; i <= str.Length - 1; i++)
                {
                    str[i] = "元素" + i;
                }
                for (int j = 0; j <= str.Length; j++)
                {
                    Console.WriteLine(str[j]);
                }
    
                Console.ReadKey();
    
  • 练习:定义一个字符串数组存放12生肖,循环遍历该数组,将元素组合成一个字符串,且元素与元素之间用' | '分割。12生肖数组元素如下:"子鼠","丑牛","寅虎","卯兔","辰龙","巳蛇","午马","未羊","申猴","酉鸡","戌狗","亥猪".
                string[] animals = new string[] { "子鼠", "丑牛", "寅虎", "卯兔", "辰龙", "巳蛇", "午马", "未羊", "申猴", "酉鸡", "戌狗", "亥猪" };
                string animalStr = "";
    
                for (int i = 0; i < animals.Length; i++)
                {
                    animalStr += animals[i];
                    if(i < animals.Length - 1)
                    {
                        animalStr += "|";
                    }
                }
    
                Console.WriteLine(animalStr);
                Console.ReadKey();

foreach  遍历数组

  • 语法
    foreach( 数组数据类型 临时变量 in 数组名)
    {
       Console.WriteLine( 临时变量 );
    }
    
    
    int[] intArray = new int[]{1,2,3,4,5,6,7,8,9};
    foreach(int i in intArray)
    {
      Console.WriteLine(i);
    }
    
     Console.ReadKey();

数组元素的初始值

  • 数组初始化完成后,各种类型的数组的默认值:
    • int[]:元素的值默认都是0;
    • float:元素的值默认都是0;
    • double:元素的值默认都是0.0;
    • string:元素的值默认都是 null;
    • bool:元素的值默认都是 false;

猜你喜欢

转载自blog.csdn.net/weixin_41232641/article/details/81943417