将项目添加到数组时,索引超出了数组的范围

时间:2019-08-15 14:48:28

标签: c# arrays

这是我的代码

public static int[] MoveZeroes(int[] arr)
    {
        // TODO: Program me
        int zeroCount = 0;
        int[] temp = { };
        int numberItems = 0;
        foreach (var a in arr)
        {

            if (a == 0)
            {
                zeroCount += 1;
            }
            else
            {
                temp[numberItems] = a;
            }

            numberItems += 1;

        }
        return new int[] { };
    }

我喜欢使用它

   int[] f = MoveZeroes(new int[] {1, 2, 1, 1, 3, 1, 0, 0, 0, 0});

但这在行上给了我错误Index was outside the bounds of the array

temp[numberItems] = a;

如何添加数组中的项目?我在做什么错了?

1 个答案:

答案 0 :(得分:1)

//some code above here $x = 1; while($row = $result->fetch_assoc()){ $uidcheck = mysqli_num_rows($result); $catname = $row['name']; $catrefno = $row['refno']; echo ' <label class="container"><input type="radio" name="catname[]" id="catname'.$x.'" value="'.$catname.'"> '.$catname.' <span class="checkmark"></span></label> <div id="selectdiv'.$x.'"><select class="form-control itnames" name="itname[]" id="itname'.$x.'" required> <option></option>'; $sql1 = "SELECT * FROM foodarea WHERE status!='deactive' and itcatname='$catname'"; $result1 = $conn->query($sql1); $uidcheck1 = mysqli_num_rows($result1); if ($uidcheck1 > 0){ while($row1 = $result1->fetch_assoc()){ $uidcheck1 = mysqli_num_rows($result1); $itname = $row1['itname']; echo '<option>'.$itname.'</option>'; } } echo '</select></div> <script>document.getElementById("catname'.$x.'").onchange = function() { var itnames = document.getElementById("selectdiv'.$x.'").innerHTML; var selectarea = document.getElementById("selectarea"); selectarea.innerHTML = !this.checked ? "none" : itnames; };</script>'; $x++; } } echo '<div id="selectarea"></div>'

这将创建一个长度为0个元素的整数数组。您不能插入其中,因为它的长度为0。

使用int[] temp = { },然后可以动态添加到其中:

List<int>