Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 而环路v。从数组中删除对象时的For循环_Loops - Fatal编程技术网

Loops 而环路v。从数组中删除对象时的For循环

Loops 而环路v。从数组中删除对象时的For循环,loops,Loops,我有一个关于使用for循环与使用while循环的问题 当我对循环使用时,当我测试I

我有一个关于使用
for
循环与使用
while
循环的问题

当我对
循环使用
时,当我测试
I<[array count]
时,它是第一次执行时的计数,还是会随着我删除对象并迭代循环而递减

我相信是后者,因为我无法拿到所有物品

for(int i=0; i < [array count] ++i) {
    //do some operations
    [array removeObjectAtIndex:i];
}

我认为我在这里做错了什么,有人能分享他们的想法吗?

当您使用for循环删除时,您必须维护索引位置,因为每次删除后数组计数都会发生变化:

for (int i = 0; i < [array count]; i++) {
    // remove object at index i
    // decrement i here cause the i++ will set it back
}

删除该索引位置后,超出该位置的元素将全部减少其索引编号1。因此,如果您在for循环中从零开始,每次递增,您将删除所有其他元素

您请求的是意见而不是答案。
我更喜欢for循环而不是while循环,因为如果使用不当,while循环可能会进入无限循环。在for循环的情况下不是那么容易。在for循环中,初始化值,检查条件,执行语句,然后在再次检查条件之前递增/递减值

谢谢你的帮助,我的问题不是减少我的体重
for (int i = 0; i < [array count]; i++) {
    // remove object at index i
    // decrement i here cause the i++ will set it back
}
while ([array count] > 0) {
    // Remove element at index 0, or remove the last element
}