3

此代码修剪空白,(仅供参考:它被认为非常快)

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 );
}

while 循环没有括号,我如何正确地将括号添加到此代码中?

while(iMean){
  // like this;
}

非常感谢!

4

2 回答 2

7

循环体是空的(实际发生的是循环条件中的递增/递减操作),所以只需添加{}

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

更长且可能更易于阅读的相同 while 循环版本是:

end = end - 1;
while (s.charCodeAt(end) < 33 )
{
    end = end - 1;
}
start = start + 1;
while (s.charCodeAt(start) < 33 )
{
    start = start + 1;
}
于 2010-06-06T16:57:51.590 回答
2

该代码不需要括号,但它确实需要一个使用本机修剪方法的选项。

Opera、Firefox 和 Chrome 都有原生的字符串原型修剪功能——其他浏览器也可以添加它。对于这个特定的方法,我想我会对 String.prototype 进行一些修改,以便在可能的情况下使用内置方法。

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);
    }
}

这可能确实很快,但我更喜欢简单-

if(!(''.trim)){
    String.prototype.trim= function(){
        return this.replace(/^\s+|\s+$/g,'');
    }
}
于 2010-06-07T02:59:51.923 回答