Does make sense to check if the length of the array is not equal to 0 before of to do the loop?
var arr = [1,2,3];
if (arr.length !== 0) {
// do loop
}
Does make sense to check if the length of the array is not equal to 0 before of to do the loop?
var arr = [1,2,3];
if (arr.length !== 0) {
// do loop
}
Share
Improve this question
edited Oct 25, 2012 at 8:44
asked Oct 25, 2012 at 8:37
user1243746user1243746
0
3 Answers
Reset to default 5In the general case it doesn't make sense. For a foreach, for, or while loop, the loop condition will prevent the loop executing anyway, so your check is redundant.
var arr = [];
for (var loopCounter = 0; loopCounter < arr.length; loopCounter++)
{
// This loop will never be entered.
}
foreach (var element in arr)
{
// This loop will never be entered.
}
var loopCounter = 0;
while (loopCounter < arr.length)
{
// This loop will never be entered.
loopCounter++;
}
However, the only time it is important is if you are using a do...while loop. In this scenario, the loop executes, and then you check your loop-condition (when it is too late). It's likely that your code would have thrown an exception inside the loop in this case, as demonstrated in the following code.
var arr = [];
var loopCounter = 0;
do
{
someMethod(arr[loopCounter]); // This will throw an error
loopCounter++;
}
while(loopCounter < arr.length);
No, the check is unnecessary. If the array has zero elements, the loop will execute zero times (assuming it is written correctly).
If the array could be null
, then checking for that would be valid, e.g.
if(arr !== null)
{
// loop
}
Well, it depends on the loop. If it's of the form:
for (i = 0; i < arr.length; i++) {
do_something_with (arr[i]);
}
then, no, the if
is superfluous, the for
loop body will not execute in this case.
However, if you've done something like (and this seems likely given that you mention a do
loop, although you may have actually meant "do the loop", so it's hard to say):
i = 0;
do {
do_something_with (arr[i]);
i++;
while (i < arr.length);
then, yes, you'll need it to avoid the problem of using arr[0]
if no such beast exists.
But I would consider that second case (check-after) "broken" since the while () {}
or for () {}
variants (check-before) would be more natural in that case.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744849737a4597056.html
评论列表(0条)