首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript代码效率

Javascript代码效率
EN

Stack Overflow用户
提问于 2010-12-10 17:41:50
回答 2查看 103关注 0票数 1

我真的不确定在这里问这个问题是否合适。如果不是,就投我的票吧。但我正在寻求关于我的纵横比函数的效率的意见。以下是确定宽高比和限制图像大小的函数。我做得怎么样?

代码语言:javascript
复制
function constrainTwoNumbers(options){

d = {
    dir: 'either', // direction: 'auto', 'vertical' or 'horizontal'. What side of the image do you want to constrain?
    orgw:0,
    orgh:0,
    target:100,
}

// merge the options with the default values
o = $.extend(d, options);

// create object to write results into
var result = [];

switch(o.dir){
    case 'either':      
        // no direction is set, limit the largest side.
        // determine what the orientation is.
        if(o.orgw > o.orgh){ //landscape
            aspect = o.orgw / o.target;
        }else if(o.orgw < o.orgh){ //portrait
            aspect = o.orgh / o.target;
        }else if(o.orgw === o.orgh){ // the image is square. Just pass both dimensions as targeted
            result.w = o.target;
            result.h = o.target;
            return result;
        }                   
        break;
    case 'horizontal':      
            aspect = o.orgw / o.target;
        break;
    case 'vertical':            
            aspect = o.orgh / o.target;
        break;
}

result.w = Math.round(o.orgw / aspect);
result.h = Math.round(o.orgh / aspect);     
return result;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-12-10 17:59:23

您可以将其压缩为一个if/else

代码语言:javascript
复制
function constrainTwoNumbers(options){

    var d = {
        dir: 'either', // direction: 'either', 'vertical' or 'horizontal'. What side of the image do you want to constrain?
        orgw:0,
        orgh:0,
        target:100
    };

    // merge the options with the default values
    var o = $.extend(d, options);

    // create object to write results into
    var result = [];
    if ((o.dir === 'either' && o.orgw > o.orgh) || (o.dir === 'horizontal'))
    {
      aspect = o.orgw / o.target;
    }
    else
    {
      aspect = o.orgh / o.target;
    }

    result.w = Math.round(o.orgw / aspect);
    result.h = Math.round(o.orgh / aspect);     
    return result;
}
票数 2
EN

Stack Overflow用户

发布于 2010-12-10 17:59:55

您可以使用http://code.google.com/closure/compiler/检查性能。

http://jslint.com/来查找内存泄漏和其他错误。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4407445

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档