Does the last element in a loop deserve a separate treatment?

前端 未结 13 2079
暖寄归人
暖寄归人 2020-12-15 18:55

When reviewing, I sometimes encounter this kind of loop:

i = begin
while ( i != end ) {    
   // ... do stuff
   if ( i == end-1 (the one-but-last element)          


        
13条回答
  •  时光取名叫无心
    2020-12-15 19:16

    I know I've seen this when people tried to join elements of an array into a comma-seperated string:

    for(i=0;i0) {
         string += ','
       }
       string += elements[i]
    }
    

    You either have that if clause in there, or you have to duplicate the string += line again at the end.

    The obvious solution in this case is

    string = elements.join(',')
    

    But the join method does the same loop internally. And there isn't always a method to do what you want.

提交回复
热议问题