【问题标题】:How to I correctly add brackets to this code如何正确地将括号添加到此代码
【发布时间】:2011-02-28 10:12:34
【问题描述】:

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

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

非常感谢!

【问题讨论】:

    标签: javascript readability semantics


    【解决方案1】:

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

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

    【讨论】:

    • 我希望这实际上会很快,因为替换功能是用 C 或 C++ 实现的(无论浏览器是用什么编写的)。它本质上有点慢,因为它使用正则表达式,但被编译成本机代码可能足以弥补这一点。
    【解决方案2】:

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

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

    【讨论】:

    • 如果他们是空的,他们在做什么吗?
    • 哦,他们正在更改变量 endstart 不是吗?
    • 也许可以添加这样的评论:{/*解释你在做什么不会有害*/}
    • 是的,副作用在表达式内部而不是正文中
    • @Mohammad 如果您在最后添加一个测试,以便仅在实际需要修剪空格时调用“slice”,它确实会加快无需修剪的情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 1970-01-01
    • 2015-10-24
    相关资源
    最近更新 更多