While going through a blog written for arrays in C++, a question arose.
//...
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
for(int i = 0; i< v.size(); i++){
v.push_back(v[i]);
}
What will happen above is it will get into an infinite loop as the size of the vector would keep on increasing.
Similar case would happen in case of JS if a plain for loop is used :
for(let i =0; i< arr.size; i++){
arr.push(arr[i])
}
But this wouldn't happen in case of a forEach
loop. Like how is forEach then implemented.
I want to know why forEach
stops adding to the array and for doesn't after the first three elements.