开发者

How to I correctly add brackets to this code

This code trims whitespace, (fyi: it's credited to be very fast)

function wSpaceTrim(s){
    var start = -1,
    end = s.length;
    while (s.charCodeAt(--end) < 33 );  //here
    while (s.charCodeAt(++start) < 33 );  //here also 
    return s.slice( start, end + 1 );
}

The while loops don't have brackets, how would i correctly add brackets to 开发者_高级运维this code?

while(iMean){
  // like this;
}

Thank you so much!


The loop bodies are empty (the actual thing that happens is the increment/decrement operation within the loop condition), so simply add {}:

while (s.charCodeAt(--end) < 33 ){}
while (s.charCodeAt(++start) < 33 ){}

A longer, and probably easier to read version of the same while loop would be:

end = end - 1;
while (s.charCodeAt(end) < 33 )
{
    end = end - 1;
}
start = start + 1;
while (s.charCodeAt(start) < 33 )
{
    start = start + 1;
}


The code doesn't need brackets, but it does need an option to use a native trim method.

Opera, Firefox and Chrome all have a native string prototype trim function- the other browsers could add it as well. For this particular method, I think I would monkey a bit with the String.prototype, so as to use the built in method where possible.

if(!String.prototype.trim){
    String.prototype.trim= function(){
        var start= -1,
        end= this.length;
        while(this.charCodeAt(--end)< 33);
        while(this.charCodeAt(++start)< 33);
        return this.slice(start, end + 1);
    }
}

This may indeed be fast, but I prefer simple-

if(!(''.trim)){
    String.prototype.trim= function(){
        return this.replace(/^\s+|\s+$/g,'');
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜